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

Time:05-11

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);
  }, []);

CodePudding user response:

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

CodePudding user response:

Use useLocation() hook.

 const { hash, pathname } = useLocation();
 console.log(pathName) // /?filter=breakfast
  • Related