0

I have an useEffect function that looks like this.

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

The getColls() functions sets the pageColl variable.

//getColls()
    const getColls = () => {
        Service.getCollections()
        .then(data => 
            setPageColl(data.collections.find(coll => coll._id === userId))
        )
    }
//states
const [pageColl, setPageColl] = useState(null);

The pageColl should be set to an object but for some reason when I try to console.log(pageColl), I get returned a null. It is as if the setPageColl was never called. I know the data was returned in getColls as I can console.log it there.

  • Sounds like the `.find(coll => coll._id === userId)` does not find a match? Double check the result before calling `setPageColl` to debug – CertainPerformance Aug 29 '20 at 21:56
  • Does this answer your question? [Why does my state not update right away in console log](https://stackoverflow.com/questions/60820754/why-does-my-state-not-update-right-away-in-console-log) – skyboyer Aug 29 '20 at 21:57

1 Answers1

0

you can't check "pageColl" state immediately after call getColls() method, because api call is asynchronous.

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

you can check like above

sivarasan
  • 320
  • 3
  • 10