May i know how to set state value after get value from function?
const getValueFunction = () => {
dispatch(fetchData(setData, 1, pages.current, rowsNumber));
}
useEffect(() => {
pages.current = 1;
getValueFunction();
const obj = data.reduce((r, { setCode }) => {
const l = setCode[0];
if (!r[l]) r[l] = [setCode];
else r[l].push(setCode);
return r;
}, {});
const sorted = Object.entries(obj).sort(([a], [b]) => a.localeCompare(b));
setOrderList(sorted);
console.log("69========"+JSON.stringify(orderList));
}, []);
When I tried to print out "orderList" for first load, it will return empty.
useEffect(() => {
pages.current = 1;
getValueFunction();
const obj = data.reduce((r, { setCode }) => {
const l = setCode[0];
if (!r[l]) r[l] = [setCode];
else r[l].push(setCode);
return r;
}, {});
const sorted = Object.entries(obj).sort(([a], [b]) => a.localeCompare(b));
setOrderList(sorted);
console.log("69========"+JSON.stringify(orderList));
}, [orderList]);
If I put orderlist in [], then it will keep loading non stop.
Please help, thank you.
2
Answers
As far as I understood your question and assuming that the variable data is the data that is populated through fetchData(), the solution is to synchronise your calculation based on data:
You need to split up the effect that wants to run once, fetching the initial data, from the effect that wants to run each time
data
changes. I’m assuming that nothing else is settingorderList
. If that’s not the case @ray’s answer suits better