2022-07-01

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.



No comments:

Post a Comment