0

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

Siraj Alam
  • 9,217
  • 9
  • 53
  • 65
Aakash Chauhan
  • 328
  • 1
  • 4
  • 14
  • Does this answer your question? [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – Emile Bergeron Nov 13 '19 at 19:54
  • i am using React hooks, can not pass a callback as second argument – Aakash Chauhan Nov 13 '19 at 20:02
  • 1
    For hooks, there's a similar question: https://stackoverflow.com/q/54069253/1218980 – Emile Bergeron Nov 13 '19 at 20:42
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Henry Woody Nov 13 '19 at 20:56

2 Answers2

3

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.

Siraj Alam
  • 9,217
  • 9
  • 53
  • 65
  • while initializing state value (with hooks) react passes useState's value to react core, hence during re-renders, data will not be lost if your previous and current state is equal, and if you clean state value manually you should be ready that it will update value in react core (it will be set to empty value) and data will be lost. – iLiA Nov 14 '19 at 10:45
0

You can just pass the 'dashboard' to the existing useEffect as dependency. The existing useEffect will work as both componentDidMount and componentDidUpdate.

So no need to write another useEffect.

useEffect(() => {
  loadDashboardData();
  console.log("campaigndata",dashboardData);
}, [dashboardData]);