-1
I’m having trouble understanding React’s life cycle.
Project summary: React repeatedly retrieves information from an API (setInterval
) with certain filters, where filters are also the result of a request to the API.
There are stations
, orders
and currentStation
(that comes from the UI).
My problem is when you do dispatch
to set a variable, it is not possible to do get
of the same variable.
Follow some parts of my component:
useEffect(() => {
listStations().then(() => {
dispatch({type: 'setLoadedStations', state: true});
});
}, []);
useEffect(() => {
listOrders(true);
}, [state.loadedStations]);
const listOrders = async (createJob?: boolean) => {
let currentStationId = state.stations[state.currentStation].id;
const orderList = await getOrders(currentStationId);
dispatch({type: 'setOrders', value: orderList});
if(createJob) {
setInterval(await listOrders, 4000);
}
}
return (
<IonButton
onClick={
(e: any) => {
e.persist();
dispatch({
type: 'setCurrentStation',
station: key
});
}
}
>
{station.title}
</IonButton>
);
In the setInterval
will always be the same state.currentStation
where the setInterval
was created. Even though later the currentStation
change.
Another solution I tried was to add a clear, but it also didn’t work because the variable is not 'guard'.
const App: React.FC = () => {
let jobId = 0;
if(createJob) {
if(jobId) clearInterval(jobId);
jobId = setInterval(await listOrders, 4000);
}
What is the correct form? Accessing a state variable without a useEffect
it is possible?
Your question is too confusing, and call
listOrders
without putting it as a dependency onuseEffect
is a mistake. You need a refactoring there.– Rafael Tavares