Search code examples
reactjsreact-hooksuse-effectreact-state

State is not updating in use-effect || data is being fetch but not update state || locally it's fetching data and update without hooks


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();
 }, []);

Solution

  • 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();
     }, []);