简体   繁体   中英

ReactJS - setting state with data fetched in use effect

I am trying to set the state of my variable with data fetched using the useEffect hook but when I call the setState() function and pass it the fetched data, the state remains null. The fetch statement works as I can log the data to the console but for some reason the setState doesn't take the data. Can anyone please tell me where I am going wrong?

Here is the useState and the useEffect:

 const [products, setProducts] = useState(null); useEffect(() => { fetch('http://127.0.0.1:8000/api_products/') .then(res => { return res.json(); }) .then((data) => { console.log(data); setProducts(data); console.log(products); }) }, [])

And here is the data that gets logged to the console. It's an array of Javascript objects:

 [ {id: 1, name: 'Cookies', shipping: 'Nationwide', image: '/images/NYC_Cookie_Choc_Chip.jpg'}, {id: 3, name: 'Banana Bread', shipping: 'Glasgow Only', image: '/images/Banana_Bread_Slice.jpg'}, {id: 4, name: 'Cupcakes', shipping: 'Glasgow Only', image: '/images/Cupcake_Double_Choc.jpg'}, {id: 2, name: 'Brownies', shipping: 'Nationwide', image: '/images/Brownies_MAcbMQf.jpg'} ]

Am I trying to set the state to be the data fetched so I can map through the array and display the data on the web page. The console.log(products) line keeps returning null. Any advice or ideas would be massively appreciated! Been scratching my head on this one for a while.

State updates are async, therefore you cannot console the output immediately. Rest assured, your data is likely being set.

The best way I've found to console the output is through useEffect:

useEffect(() => {
    console.log(products)
    //Or, take some action
  }, [products])

Similarly, you'll need to useEffect if you want to act upon a state change immediately once it's complete. I've shown this in my comment above for Or, take some action .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM