Home > Mobile >  why is my state not updating after axios request is resolved
why is my state not updating after axios request is resolved

Time:07-23

Basically, I have defined a state called predictedCrop which is an array, however after the axios post request, I get back data from the backend and when I console.log that data, it shows however when I am setting the state nothing shows apart from an empty array.

This is the function

const [predictedCrop , setPredictedCrop] = useState([])


const getWeatherDetails = async() => {
        try {
            const response = await axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&units=metric&appid=${API_KEY}`)
            console.log(response.data)
            
            //Send temp and humidity to backend for analysis
            const dataToSend = response.data
            const sentWeatherData = await axios.post("http://localhost:4000/analysis" , {
                data: dataToSend
            }).then((response) => {
                let dataObject = response.data;
                setPredictedCrop(dataObject)
                console.log(predictedCrop)
            })

        } catch {
            console.log("error")
        }
    }

I am certain that the data is reaching the frontend as when i console.log(data.response) I get the data back. I have also tried assigning a normal variable to it and console.log that variable and the data shows, It is only when I place it in the state that it does not work.

CodePudding user response:

useState() is asynchronous. React does not guarantee that the state changes are applied immediately. useState() does not always immediately update the component. Think of useState() as a request rather than an immediate command to update the component. So you can not see the result immediately inside the method.you can use useEffect:

useEffect(() => {
   console.log(predictedCrop )
}, [predictedCrop ]);

CodePudding user response:

Make the GET request when the page renders . so use the useEffect hook to call your function getWeatherDetails when the component mounts .

try it like this :

useEffect(() => {
   const getWeatherDetails = async() => {
        try {
            const response = await axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&units=metric&appid=${API_KEY}`)
            console.log(response.data)
            
            //Send temp and humidity to backend for analysis
            const dataToSend = response.data
            const sentWeatherData = await axios.post("http://localhost:4000/analysis" , {
                data: dataToSend
            }).then((response) => {
                let dataObject = response.data;
                setPredictedCrop(dataObject)
                console.log(predictedCrop)
            })

        } catch {
            console.log("error")
        }
    }
}, [predictedCrop ]);
  • Related