state is not updating using React hook

This is a function which has to be called when the component mounts on DOM

const [dashboardData, setDashboardData] = useState('');

const loadDashboardData = () => {
    console.log("Loading Dashboard Data ", campaign);
    Utils.request({
      url: `campaign/user/info`
    }).then(
      res => {
        console.log("dashboard data" , res.data)
        setDashboardData(res.data);
      },
      err => console.log(err)
    )
  }

 useEffect(() => {

    loadDashboardData();
    console.log("campaigndata",dashboardData);

  }, []);

when I console dashboardData in useEffect, it shows nothing but a string i.e campaigndata which I passed as the first argument in console.log. what I think that my dashboard state variable is not getting updated

Answer

Answer

Write another useEffect just for dashboardData.

useEffect(() => {
    console.log("campaigndata",dashboardData);

}, [dashboardData]);

Explanation

Your useEffect is taking an empty array as the second argument, which makes it run only the first time (as DidMount), so it won’t re-run on component re-render after changing the state, that’s why it is showing empty string as the initial state.
Writing another useEffect for the variable dashboardData will run as many times as the dashboardData changes.

Leave a Reply

Your email address will not be published. Required fields are marked *