0

After setting statevariable in a function, following lines are not able to read the new values. The function is present in a functional component. Seems like setting state variable is an async function and need some time to update. On refresh of UI the value of statevariable is correct but not while the function is in progress. I read about combination of useEffect and useRef as I need to pass local variable of functions to useEffect also but that is not working. The UI is just stuck when I use my solution.

Original code

export const SummaryTab: React.FC<any> = (props) => {
    const [stateVariable,setstateVariable] = useState(false)


const function = () => {
        
        getDetails(details_request, token)
            .then((res) => {
                let details: any[] = []
                let data = getData()
                data = getData()
                details = getData2()
                setstateVariable(updateStateVariable(Array.from(data)));  //After this all should come under useEffect
                details = sort(details)
                if (data.size > 0) {
                    console.log("stateVariable " + stateVariable);     //Value is stale and not updated correctly
                    let runs = [...data]
                    if (stateVariable==false) {
                        functionA(runs)
                        functionB(runs)
                    } else {
                        functionA(runs)
                    }
                    details = sort(details)
                }
            }).catch(error => {
                console.log(error)
            });
    }

My solution

export const SummaryTab: React.FC<any> = (props) => {
  const [stateVariable, setstateVariable] = useState(false);
  const dataRef = useRef<any>(null);
  const detailsRef = useRef<any[]>([]);

  useEffect(() => {
    console.log("stateVariable " + stateVariable);

    detailsRef.current = sort(detailsRef.current)


    if (dataRef.current && dataRef.current.size > 0) {
      let runs = [...dataRef.current];
      if (stateVariable === false) {
        functionA(runs);
        functionB(runs);
      } else {
        functionA(runs);
      }
      detailsRef.current = sort(detailsRef.current);
    }
  }, [stateVariable]);

  const fetchData = () => {


    getDetails(details_request, token)
      .then((res) => {
        let details: any[] = []
        let data = new Set<string>()
        detailsRef.current=details
        dataRef.current = data
        detailsRef = getData2();
        dataRef = getData();
        detailsRef.current=details
        dataRef.current = data
        setstateVariable(updateStateVariable(Array.from(data)));
      })
      .catch((error) => {
        console.log(error);
      });
  };

  
  // Rest of the component code...
};


Mehul Parmar
  • 347
  • 4
  • 21
  • 1
    See this answer: [The useState set method is not reflecting a change immediately](https://stackoverflow.com/a/58877875) option 3. So use your first example but store `updateStateVariable(Array.from(data))` in a variable, and then reference that variable from then on within your function when you need the latest value. – Nick Parsons Jun 14 '23 at 11:42

0 Answers0