Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React router how to get current path and look for its updates

Hello I have question how can I get current path of app with search params and look for its updates. For example I have localhost3000/?filter=breakfastdinner and I want to go back to localhost3000/?filter=breakfast. I want to wait for URL updates to use useEffect.

useEffect(() => {
    for (let i = 0; i <= recipeTypesArray.length - 1; i++) {
      if (searchParams.get("filter")?.includes(recipeTypesArray[i])) {
        dispatch(
          recipeAction.addFilters({
            content: recipeTypesArray[i],
            filterName: "filterTypes",
          })
        );
      }
      if (!searchParams.get("filter")?.includes(recipeTypesArray[i])) {
        dispatch(
          recipeAction.removeFilters({
            content: recipeTypesArray[i],
            filterName: "filterTypes",
          })
        );
      }
    }
    initial = false;
    console.log(chosenFiltersTypes);
  }, []);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What about using useRouter(); and pass the route in the useEffect deps, something like:

const { asPath } = useRouter(); // asPath or whatever from the router

useEffect(() => {
    for (let i = 0; i <= recipeTypesArray.length - 1; i++) {
      if (searchParams.get("filter")?.includes(recipeTypesArray[i])) {
        dispatch(
          recipeAction.addFilters({
            content: recipeTypesArray[i],
            filterName: "filterTypes",
          })
        );
      }
      if (!searchParams.get("filter")?.includes(recipeTypesArray[i])) {
        dispatch(
          recipeAction.removeFilters({
            content: recipeTypesArray[i],
            filterName: "filterTypes",
          })
        );
      }
    }
    initial = false;
    console.log(chosenFiltersTypes);
  }, [asPath]);

Edit:

For react-router how about these hooks (based on your goal)?

useHistory
useLocation
useParams
useRouteMatch

I think all of them are supported in v6 too.

https://v5.reactrouter.com/web/api/Hooks

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading