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?
>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]);