0

I am working on a simple crypto ticker app . I am using an api to get details about cryptos and this is how fetching look likes currently.

const [ Data , setData ] = useState([]);
  useEffect(() => {

    const interval = setInterval(() => {
      fetch('https://api.coindcx.com/exchange/ticker').then((result) => {
      result.json().then((resp) => {
        console.log(resp)
        setData(resp);
        console.log(Data)
        setLoading(false);
      })
    })
    }, 3000);
    return () => clearInterval(interval);
  },[])

I am using interval so that data is updated every 3 seconds.

The problem I am facing is that in the useEffect setData is not setting data. console.log(resp) is working correctly but console.log(Data) is loggin out an empty array in console whereas I want data and resp to be the same.

VATSAL JAIN
  • 561
  • 3
  • 18
  • Does this answer your question? [Why is setState in reactjs Async instead of Sync?](https://stackoverflow.com/questions/36085726/why-is-setstate-in-reactjs-async-instead-of-sync) – Shubham Dixit Jun 12 '22 at 07:16
  • No. Can you please solve my problem? – VATSAL JAIN Jun 12 '22 at 07:17
  • 1
    setState happens asynchronously ,so you cant just predict when it gonna happen ,there was callback mechanism in classes for setState method but not in hooks .You can try fitting console.log(Data) in setTimeout for lets say 2000 ms ,assuming it will update in that time – Shubham Dixit Jun 12 '22 at 07:18
  • 1
    That's because `useState` is not performed right away. If you will log data in the render function you will see the result. – Reut Schremer Jun 12 '22 at 07:18
  • 1
    Does this answer your question? [React, state not getting updated when calling the related setState](https://stackoverflow.com/questions/71004802/react-state-not-getting-updated-when-calling-the-related-setstate) – Youssouf Oumar Jun 12 '22 at 07:24
  • 2
    check this one https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately – Reut Schremer Jun 12 '22 at 07:27

1 Answers1

2

If you want to console.log your data You need to use useEffect for console.log, because setstate in async and not sync

useEffect(() => {
const interval = setInterval(() => {
  fetch('https://api.coindcx.com/exchange/ticker').then((result) => {
  result.json().then((resp) => {
    console.log(resp)
    setData(resp);
    console.log(Data)
    setLoading(false);
  })
})
}, 3000);
return () => clearInterval(interval);
  },[])

and than:

useEffect(() =>
{
console.log(data)
}
,[data])
yanir midler
  • 2,153
  • 1
  • 4
  • 16