0

I'm trying to get my data on API, when i console.log for the first time, i still get the data. But when i'm trying to set it into my state, it returned undefined. What's wrong with my code?

```

    useEffect(()=>{
    axios.get(`https://angga605090.herokuapp.com/homeicon`)
      .then(res => {
          console.log(res.data)
          setHomeIcon(res.data)
          console.log(homeicon)
      }).catch((err)=>{
          console.log(err)
      })
},[])


const [homeicon,setHomeIcon]=useState()

```

when i console. log, my data looks like this:

[{"id": 1, "img": "https://titan.email/wp-content/uploads/2019/12/email-introduction.png", "name": "Memperkenalkan Diri"}, {"id": 2, "img": "https://cdn.wpforms.com/wp-content/uploads/2017/04/thank-you-page-examples.jpg", "name": "Mengucapkan Terima Kasih"}, {"id": 3, "img": "https://media.lifehack.org/wp-content/files/2018/03/27233542/powerful-daily-routine.001-370x208@2x.jpeg", "name": "Kegiatan Sehari-hari"}, {"id": 4, "img": "https://www.goodnewsfromindonesia.id/uploads/post/large-maxresdefault-6-b21cac43d55730ce33a5e9d52af656dd.jpg", "name": "Pengenalan Angka"}, {"id": 5, "img": "https://s3.amazonaws.com/southfloridareporter/wp-content/uploads/2016/04/17080327/days-of-the-year-logo.jpg", "name": "Pengenalan Hari"}]

1 Answers1

0

Use state is asynchronous so changes can not be seen immediatelly.

See: useState set method not reflecting change immediately

You can do the following in order to see the state change:

useEffect(()=>{
    axios.get(`https://angga605090.herokuapp.com/homeicon`)
      .then(res => {
          console.log(res.data)
          setHomeIcon(res.data)
          // console.log(homeicon) <-- remove that line
      }).catch((err)=>{
          console.log(err)
      })
},[])

useEffect(() => {   <-- add this hook
  console.log(homeicon);
},[homeicon])
D10S
  • 1,468
  • 2
  • 7
  • 13