when is console.log() projects result show but when i console log data state that is just showing initialstate(data) with empty array of projects
const [data, setdata] = useState({
projects: []
});
useEffect(() => {
const fetchData = async () => {
const res = await axios('http://localhost:5000/api/projects');
const projects = await res.data;
setdata({ projects: projects });
console.log(data);
};
fetchData();
}, []);
data
is not yet initialized, useEffect
runs after the render
lifecycle, so such logging is just useless.
In any way, the state should be updated, you just didn't check "if the state is updated" right.
const [data, setdata] = useState({
projects: []
});
useEffect(() => {
const fetchData = async () => {
const res = await axios('http://localhost:5000/api/projects');
const projects = await res.data;
setdata({ projects: projects });
// v Always results { projects: [] }
console.log(data);
};
fetchData();
}, []);