This is a useEffect function, shopId is updated once, so I assume it run once. even though I call the setOrder function the order variable is not recongnized as updated in here, it is updated in other places. Is there a way to make the setInterval use the updated order variable?
useEffect(() => {
setInterval(() => {
if (shopId != null) {
// console.log(order.length);
if (order.length == 0) {
FindCustomer()
.then((r) => JSON.parse(r))
.then((r) => {
console.log(r, "r");
let col = r["col"];
setOrder(col);
});
}
}
}, 10000); // fetch updates every 5 seconds
}, [shopId]);
We tried making the setInterval function call a different function, that should check length of order, but got same result. Thanks in advance.
Your effect has a dependency on order
(and technically on setOrder
), which was omitted from the dependency array. Add it, so the effect can be updated when that value changes.
You should also not assume that the effect will only execute once. Especially if you need it to be updated when a dependency changes. The effect should return a function which cleans up side effects (e.g. the interval), before it gets invoked again when a dependency changes.
For example:
useEffect(() => {
const interval = setInterval(() => {
if (shopId != null) {
// console.log(order.length);
if (order.length == 0) {
FindCustomer()
.then((r) => JSON.parse(r))
.then((r) => {
console.log(r, "r");
let col = r["col"];
setOrder(col);
});
}
}
}, 10000); // fetch updates every 5 seconds
return () => clearInterval(interval);
}, [shopId, order, setOrder]);