Unable to set response data in my local state using hooks in react

  javascript, reactjs

I am using Functional components and am a beginner.I am receiving the response from API successfully but when I am setting it to the local useState variable, it still remains empty.I am unable to understand how to fix this.

Approach 1:

const [sites,setSites]=useState([]);
useEffect(()=>{
    getAllSites().then(res=>{
      console.log("res",res.sites);//response received successfully
      setSites(res.sites);
      console.log(sites);//return empty array
    })
    .catch(err=>{
      console.log("Error:",err);
    })
  },[])

Approach 2:

const [sites,setSites]=useState([]);
useEffect(()=>{
    getAllSites().then(res=>{
      console.log("res",res.sites);
    },(res)=>{
     setSites(res);//thought maybe because of async nature, so tried using callback but still empty 
})
    .catch(err=>{
      console.log("Error:",err);
    })
  },[])

Can someone help me out with this?

Source: Ask Javascript Questions

LEAVE A COMMENT