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

Setting a state but still getting error when trying to use after it

I’m trying to get pinned article

const getCurrentlyPinned = async() =>{
      setLoader(true)
      await firestore()
        .collection('admin_control')
        .doc('currently_Pinned')
        .get()
        .then(snapshot =>{
          const data = snapshot.data();
          setpinnedNewsID(data.pinnedNewsId)
        })
    }

useEffect(() => {
      getCurrentlyPinned().then(()=>{
         console.log(pinnedNewsID)
     })
    }, [])

therefore calling it from useEffect and console logging it in .then function, but I’m getting its value as undefined. I dont know why I’m getting this.

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 :

That’s a very common stuff, I guess there must be some similar question over stackoverflow but let me answer it for you. States are asynchronous so it takes a bit time of course to set it.
Just do the following stuff.

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

the state which you’re setting in firebase function, just pass it in the dependency array of another useEffect so that you will console.log only when its value has been changed(or set)

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