Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
React, not able to not run the logic inside useEffect after url change

I have this in my component:

const [filtersFetched, setFiltersFetched] = React.useState(false);
useEffect(() => {
  if (history.location.search.includes("publisher_id=") && !filtersFetched) {
    fetchAllAxiosResponse <
      API.Publisher >
      (CatalogService.getPublishers, new URLSearchParams(), 1500)
        .then((data) => {
          setPublishers(data);
          setFiltersFetched(true);
        })
        .catch((err) => {
          setFiltersFetched(true);
        });
  }
}, [filtersFetched, history.location]);

const asyncFilters = {
  publisher_id: filtersFetched,
};

The idea is that the useEFfect runs every time that the history stack changes, but if it has already been run once, it should not run again. Hence the !filtersFetched in the first condition

How can I avoid that? Because every time I change the location (I'm replacing the url in other part of the app), filtersFetched is reset to false, and the whole fetch happens again.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Thats's happening because whenever you change the url, the component gets unmounted. And when you come back, it's a fresh component, which means filtersFetched state will be at its initial value. I assume you declared it like this:

const [filtersFetched, setFiltersFetched] = useState(false);

That's the normal behaviour in React. If it's really important for you that it shouldn't run on mount after url change, you could use localStorage to remember the value of filtersFetched. For that, change your useEffect to:

useEffect(() => {
  if (history.location.search.includes("publisher_id=") && !filtersFetched) {
    fetchAllAxiosResponse <
      API.Publisher >
      (CatalogService.getPublishers, new URLSearchParams(), 1500)
        .then((data) => {
          setPublishers(data);
        })
        .catch((err) => {
          console.log(err);
        })
        .finally(() => {
          setFiltersFetched(true);
          localStorage.setItem("filtersFetched", JSON.stringify(true));
        });
  }
}, [filtersFetched, history.location]);

And set the initial value of filtersFetched like below instead of what you had before:

const initialFiltersFetchedValue = localStorage.getItem("filtersFetched")
  ? JSON.parse(localStorage.getItem("filtersFetched"))
  : false;
const [filtersFetched, setFiltersFetched] = useState(initialFiltersFetchedValue);

And if you wanna take it further, you could implement a system of cashing your HTTP queries, with a library like React Query.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda