Home > Blockchain >  A function with async is returning a fulfilled promise, how to access the data within
A function with async is returning a fulfilled promise, how to access the data within

Time:09-20

So, basically, I use React, and everything that is related to MERN stack. I am just learning so I'd like to learn the most I can. I've encountered a problem, I am trying to fetch todos from a database and I use useState hook to get it done. I know that useState is on its own a promise, that works asynchronously but I don't know how to solve it.

const [todos, setTodos] = useState(async () => {
        const dataToSet = await axios.get(`/${window.localStorage.getItem('userId')}`)
        console.log(dataToSet.data)
        return dataToSet.data
    })

    useEffect(() => {
        console.log(todos)
    }, [todos])

Here's what I am getting in the console

So, as you see. I return the dataToSet.data that is correct in the console. Finally, what I get back is the promise.

CodePudding user response:

Because you're setting the state to a Promise:

useState(async () => { /*...*/ });

Set the state to a value. For example, if todos is an array, make it by default an empty array:

const [todos, setTodos] = useState([]);

Then update state in your asynchronous operation. Assuming that operation is meant to execute only once when the component first loads, put it in a useEffect with an empty dependency array:

useEffect(() => {
  const getData = async () => {
    const dataToSet = await axios.get(`/${window.localStorage.getItem('userId')}`)
    console.log(dataToSet.data);
    setTodos(dataToSet.data);
  };
  getData();
}, []);

The call to setTodos(dataToSet.data) will update state, which will trigger the component to re-render with the new state.

  • Related