Categories
React Answers

How to Set Initial React State from API Data?

Spread the love

Sometimes, we want to set initial React state from API data.

In this article, we’ll look at how to set initial React state from API data.

Set Initial React State from API Data

To set initial React state from API data, we can make the request in the useEffect callback.

And we pass in an empty array as the 2nd argument to only make it run when the component mounts.

For instance, we write:

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

export default function App() {
  const [ans, setAns] = useState();

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

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

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

We have the getAns function that makes a GET request with fetch.

Then we call res.json to return a promise with the response JSON data.

Next, we call setAns to set the value of ans.

We call getAns in the useEffect callback to run it.

And the callback only runs when the component mounts since we pass in an empty array into useEffect.

Conclusion

To set initial React state from API data, we can make the request in the useEffect callback.

And we pass in an empty array as the 2nd argument to only make it run when the component mounts.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *