Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Status is not updated React

Why doesn’t the "product" state change in this function? I am getting data to display in a table. But this data is not displayed because the product state is not updated.

  const [datos, setDatos] = useState([]);

  useEffect(() => {
    const fetchDatos = async () => {
    try {
        const response = await axios.get(`${process.env.REACT_APP_API_URL}/data`);
        setDatos(response.data);
        console.log(datos)
    } catch (err) {
        console.log(err.response.data)
    }
}
fetchDatos();
  }, []);
  

I’m trying to display the "producto" data in a table but it’s not showing anything because the "producto" state is not updated in time. The data comes from my MongoDB database. what am I doing wrong?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

setDatos function provided by useState is asynchronous. Therefore, when you try to log the datos state using console.log(datos) after calling setDatos, you may not see the updated state value.

Solution is to add another useEffect hook to monitor changes in the datos

useEffect(() => {
  console.log(datos);
}, [datos]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading