Life cycle and React variables (state and useEffect)

Asked

Viewed 34 times

-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 on useEffect is a mistake. You need a refactoring there.

1 answer

-1


The state variables are outdated because of the operation of the closure, I suggest you read some article about it so that you better understand the functioning.

I didn’t fully understand your question, but I will leave a solution related to keeping the value of an updated state within a function called in a setInterval.

It consists of keeping the used states within the setInterval updated by including these states in the useEffect dependency array, I recommend you run this example to better understand how it works:

const useTimer = (filter) => {
  useEffect(() => {
    console.log("Criando novo interval");
    const intervalId = setInterval(() => {
      console.log(`Chamou função com o valor: ${filter}`);
    }, 1000);

    return () => {
      console.log("Valor do filter foi alterado, limpando interval");
      clearInterval(intervalId);
    };
  }, [filter]);
};

const ComponentePai = () => {
  const [filter, setFilter] = useState("1");
  useTimer(filter);

  return (
    <select
      onChange={(e) => {
        setFilter(e.target.value);
      }}
    >
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
  );
};
  • 1

    Yes, that is correct. I have however understood the true potential of Hooks and how to create my own useFunctions. I marked how I accept your response so that I can help new people in the Act in the future.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.