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...
};