Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading