0

I am working on a app which get to and from value from server side for that i dispatch action in one of the useEffect and after getting the value I pass it to setState inside the useEffect but it is not working. I have no idea why.

Here how i have did this

const [timeSpan, setTimeSpan] = React.useState("Monthly");
  const [year, setYear] = React.useState(2020);
  const [tabValue, setTabValue] = React.useState(0);
  const [spanData, setSpanData] = React.useState([]);
  const [dataType, setDataType] = React.useState("aim");
  const [dataTo, setDataTo] = React.useState("");
  const [dataFrom, setDataFrom] = React.useState("");
     const {
        loading,
        duration,
        period,
        type,
        dispensingOverviewData,
        overviewDataLoading,
        defaultMonth,
      } = dispensingData;
      const { count } = dispensingOverviewData;
    
    
      useEffect(() => {
        getFilterData(year);    <--- This one is getting to and from data from server
      }, [getFilterData, year]);
    
      useEffect(() => {
        const to = defaultMonth.to;          <-- Here I am setting value to localState
        const from = defaultMonth.from;
        setDataTo(to);
        setDataFrom(from);
      }, [defaultMonth]);
    
      useEffect(() => {
        getOverviewData(year, dataTo, dataFrom, dataType);   <-- Here i am passing value to other action
      }, [getOverviewData, year, dataTo, dataFrom, dataType]);

I am adding this to localState because once the component is mount user can chanage the value of to and from as well.

aditya kumar
  • 2,905
  • 10
  • 39
  • 79
  • Could you please refer to this link? https://stackoverflow.com/questions/53715465/can-i-set-state-inside-a-useeffect-hook – K.Raj. Nov 04 '20 at 11:28
  • i have gone through this and i tried but it did not worked. I don't know why – aditya kumar Nov 04 '20 at 11:39
  • Just to make sure, you didn't forget to first add the useState hooks to your code before using the state and its setter? For ex. `const [dataTo, setDataTo] = useState();`. Your code doesn't show them, so just a thought. You'd have to show more code and explain what errors you're getting to get better answer otherwise I guess. – Kasparas Anusauskas Nov 04 '20 at 11:48
  • I have updated my question with all the local state i am use. It is defined here. – aditya kumar Nov 04 '20 at 12:11
  • Im guessing the problem is in your second `useEffect`. Can you verify that it is triggered when defaultMonth changes? – Tasos Nov 04 '20 at 12:21
  • All three effect are triggered in sequence i did try them by putting `console.log()` in every one of them – aditya kumar Nov 04 '20 at 12:25

0 Answers0