React hooks updated state not passed to function

Viewed 68

I am trying to save an api response using react hooksand pass it to a fucntion drawChart. In this code the update state of the object is not being passed to my function. What would be the proper way of passing the updated state of the object to the function drawChart ?

  useEffect(() => {
    axios.get(url)
      .then(response => {
        var obj = JSON.parse(response.data)
        setResponseMonthly(obj);
      })
      .then(response=>{
        drawChart(responseMonthly, 'month')
      })
      .catch(err => console.log(err))
  },[]);
2 Answers

when you change your state , the component must be rernder to get new state

you can write another useEffect like this

  useEffect(() => {
    axios.get(url)
      .then(response => {
        var obj = JSON.parse(response.data)
        setResponseMonthly(obj);
      })
      .catch(err => console.log(err))
  },[]);


useEffect(() => {
    if(responseMonthly) drawChart(responseMonthly, 'month')
},[responseMonthly]);

or you can call your function like this

 useEffect(() => {
    axios.get(url)
      .then(response => {
        var obj = JSON.parse(response.data)
        setResponseMonthly(obj);
        drawChart(obj, 'month')
      })
      .catch(err => console.log(err))
  },[]);

You need to pass whatever variable you want to change within the []

    useEffect(() => {
        if (responseMonthly) {
          drawChart(responseMonthly, 'month')
          return 
        }

        axios.get(url)
          .then(response => {
            var obj = JSON.parse(response.data)
            setResponseMonthly(obj);
          })
          .catch(err => console.log(err))
      },[responseMonthly]);
Related