Categories
React Answers

How to Fix the “Objects are not valid as a React child (found: [object Promise])” Error When Developing React Apps?

Sometimes, we may run into the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps.

In this article, we’ll look at how to fix the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps.

Fix the "Objects are not valid as a React child (found: [object Promise])" Error When Developing React Apps

To fix the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps, we should make sure the states we’re rendering aren’t set to promises.

For instance, we write:

import React, { useEffect, useState } from "react";

export default function App() {
  const [val, setVal] = useState();

  const getAnswer = async () => {
    const res = await fetch("https://yesno.wtf/api");
    const json = await res.json();
    setVal(json.answer);
  };

  useEffect(() => {
    getAnswer();
  }, []);

  return <div>{val}</div>;
}

We create the getAnswer function that gets data from an API with fetch.

Then we call res.json to convert the response data into a JSON object.

We put await before res.json to get the actual data object instead of a promise assigned to json.

Next, we call setVal to set val to the value of json.answer.

Then in the useEffect callback, we call getAnswer to get the data when the component mounts.

We pass in an empty array into useEffect to make sure the useEffect callback only runs when the component mounts.

And finally, we display the value of val in the div.

Conclusion

To fix the "Objects are not valid as a React child (found: [object Promise])" Error when developing React apps, we should make sure the states we’re rendering aren’t set to promises.

Categories
React Answers

How to Only Allow Numbers to be Entered in an Input in React?

Sometimes, we want to only allow numbers to be entered in an input in React.

In this article, we’ll look at how to only allow numbers to be entered in an input in React.

Only Allow Numbers to be Entered in an Input in React

To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted.

Then in the onChange handler, we only set the value of the input when the inputted value is valid.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [val, setVal] = useState(0);

  return (
    <div>
      <input
        type="text"
        pattern="[0-9]*"
        value={val}
        onChange={(e) =>
          setVal((v) => (e.target.validity.valid ? e.target.value : v))
        }
      />
    </div>
  );
}

We create the val state with the useState hook.

And we set that as the value of the value prop.

Then we add the pattern attribute and set it to a regex that only matches digits.

Finally, the onChange prop is set to a function that calls setVal with a function that takes the existing value of val, which is v.

And we check if the inputted value is valid with e.target.validity.valid .

If it is, we return the current inputted value, which is stored in e.target.value.

Otherwise, we return the current value of val which is v.

Conclusion

To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted.

Then in the onChange handler, we only set the value of the input when the inputted value is valid.

Categories
React Answers

How to Set the Port of the Dev Server in a Next.js Project?

Sometimes, we want to set the port of the dev server in a Next.js project.

In this article, we’ll look at how to set the port of the dev server in a Next.js project.

Set the Port of the Dev Server in a Next.js Project

To set the port of the dev server in a Next.js project, we can add the -p option to the dev command in package.json.

For instance, we write:

"scripts": { 
  "dev": "next -p 8080" 
},

to set the dev server to serve the project on port 8080.

We can also set the PORT environment variable before we run the dev script.

To do this, we type in:

PORT=8080 npx next dev

into the command to run the dev server on port 8080.

Conclusion

To set the port of the dev server in a Next.js project, we can add the -p option to the dev command in package.json.

We can also set the PORT environment variable before we run the dev script.

Categories
React Answers

How to Update and Merge State Object using React useState Hook?

Sometimes, we want to update and merge state object using React useState hook.

In this article, we’ll look at how to Update and merge state object using React useState hook.

Update and Merge State Object using React useState Hook

To Update and merge state object using React useState hook, we can pass in a function into the state setter function.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [count, setCount] = useState(0);

  const increment = () => {
    setCount((count) => count + 1);
  };

  return (
    <div>
      <div>{count}</div>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

to create the count state with the useState hook.

And to make sure we update count by incrementing the current count value, we pass in a function that takes the current count value and return the new count value into the setCount state setter function.

Then we set that as the value of the onClick prop of the button to run increment when we click it.

Therefore, when we click the button, we see the count incremented by 1.

Conclusion

To Update and merge state object using React useState hook, we can pass in a function into the state setter function.

Categories
React Answers

How to Detect Page Refresh by Pressing F5 in a React Component?

Sometimes, we want to detect page refresh by pressing F5 in a React component.

In this article, we’ll look at how to detect page refresh by pressing F5 in a React component.

Detect Page Refresh by Pressing F5 in a React Component

To detect page refresh by pressing F5 in a React component, we can use the performance.navigation.type property to check what kind of navigation is done.

If the value is 1, then we refreshed the page manually with the F5 key.

For instance, we write:

import React, { useEffect } from "react";

export default function App() {
  useEffect(() => {
    if (performance.navigation.type === 1) {
      console.log("This page is reloaded");
    } else {
      console.log("This page is not reloaded");
    }
  });

  return <div></div>;
}

We check that the performance.navigation.type value is 1.

If it is, we log 'This page is reloaded'.

This code is in a function in the useEffect hook so that it runs every time rendering is done.

Therefore, when we press F5 to refresh, we should see 'This page is reloaded' logged in the console.

Conclusion

To detect page refresh by pressing F5 in a React component, we can use the performance.navigation.type property to check what kind of navigation is done.

If the value is 1, then we refreshed the page manually with the F5 key.