Home > Mobile >  ReactJS: Wait for data before saving to useState
ReactJS: Wait for data before saving to useState

Time:12-18

i have the following problem:

I'm fetching data (true or false value) from my database and want to save it to a useState. I'm using async/await for the fetch. Because of that, the value saved to my state is undefined.

Here is my code:

const [myState, setMyState] = useState();

useEffect(() => {
  myFunction()
  async function myFunction () {
    const req = await fetch("http://localhost:3001/api/getdata", {
        headers: {
            "x-access-token": sessionStorage.getItem("token")
        }
    })

    const data = await req.json()
    console.log("fetched data value: "   data)

    // This is undefined in the console
    setMyState(data)

    // I already tried this, but await does not affect a setState
    // const blah = await setMyState(data)
  } 
}, [])

How can i wait for the data to be fetched before saving it to the state? Thanks for helping.

CodePudding user response:

Since you have an async function, you can use then() promise handlers to only set the state once the data is fetched. Here's an example:

const [myState, setMyState] = useState();

useEffect(() => {
  myFunction()
  async function myFunction () {
    // Call then() after using fetch to pass the result into a callback that saves state

    fetch("http://localhost:3001/api/getdata", {
        headers: {
            "x-access-token": sessionStorage.getItem("token")
        }
    }).then(
      (response) => response.json()
    ).then(
      (data) => setMyState(data)
    )
  } 
}, [])

Check out the official web api for fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

CodePudding user response:

What you have should work but you should set an initial value for your useState to an empty array or what ever it is your data will eventually be or at least null or undefined explicitly that way you know what state it is before its loaded Below is stackblitz with a working example

https://stackblitz.com/edit/react-pimpje?file=src/App.js

function App() {
  const [myState, setMyState] = React.useState(null);

  React.useEffect(() => {
    async function myFunction() {
      /**
       * https://apipheny.io/free-api/
       */
      const req = await fetch('https://api.publicapis.org/entries');
      const data = await req.json();

      console.log('fetched data value: ', data);

      setMyState(data);
    }

    myFunction();
  }, []);

  return <div>{myState && <pre>{JSON.stringify(myState, null, 2)}</pre>}</div>;
}
  • Related