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
JavaScript Answers

How to Use the Fetch API to Get an Image from a URL?

Sometimes, we want to use fetch API to Get an image from a URL.

In this article, we’ll look at how to use fetch API to Get an image from a URL.

Use the Fetch API to Get an Image from a URL

To use fetch API to Get an image from a URL, we can call the blob method on the response object.

Then we can use FileReader to read the blob into a base64 string.

For instance, we write:

const imageUrl = "https://i.picsum.photos/id/566/200/300.jpg?hmac=gDpaVMLNupk7AufUDLFHttohsJ9-C17P7L-QKsVgUQU";

(async () => {
  const response = await fetch(imageUrl)
  const imageBlob = await response.blob()
  const reader = new FileReader();
  reader.readAsDataURL(imageBlob);
  reader.onloadend = () => {
    const base64data = reader.result;
    console.log(base64data);
  }
})()

We call fetch with imageUrl to make a GET request to the imageUrl and return a promise with the response object.

Then we call response.blob to return a promise with the blob data of the image.

Next, we create a FileReader instance and set the onloadend property to a function that gets the base64 string from the blob with the reader.result property.

And then we log the base64data value in the console.

Conclusion

To use fetch API to Get an image from a URL, we can call the blob method on the response object.

Then we can use FileReader to read the blob into a base64 string.