Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need useEffect hook invoke when URL changes

I am trying to have this component load data depending on its current url whether /global or /my-posts. The useEffect() grabs the data from the first loading of the component but when i change to another url i expected useEffect to check the url again and load the correct data but instead i'm stuck with the data from the first load. How do i get useEffect to invoke every time i click between different urls like /global and /my-posts url.

export default function Dashboard() {
  const [allRecipes, setAllRecipes] = useState([]);
  const [myRecipes, setMyRecipes] = useState([]);
  const currentUrl = window.location.pathname;

  useEffect(() => {
    if (currentUrl === '/dashboard/global') {
      console.log('hello');
      trackPromise(
        RecipeService.getAllRecipes()
          .then((data) => {
            setAllRecipes(data);
          }),
      );
    } else if (currentUrl === '/dashboard/my-posts') {
      console.log('hi');
      trackPromise(
        RecipeService.getRecipes()
          .then((data) => {
            setMyRecipes(data);
          }),
      );
    }
  }, []);
  console.log(window.location.pathname);
  return (
    <>
      <div className="dashboard">
        <DashboardHeader />
        <div className="created-posts">
          {allRecipes.length !== 0
            ? allRecipes.map((recipe) => <Post recipe={recipe} key={uuidv1()} />)
            : null}
          {myRecipes.length !== 0
            ? myRecipes.recipes.map((recipe) => <Post recipe={recipe} key={uuidv1()} />)
            : null}
          {currentUrl === '/dashboard/create' ? <CreateForm /> : null}
          <LoadingIndicator />
        </div>
      </div>
    </>
  );
}

1 Answers

to make React.useEffect run on every currentUrl change, you have to add it to useEffect dependencies array.

// first we need to control the state of window.location.pathname by react not the browser
// and make react state be the only source of truth.
const pathname = window.location.pathname

// manage currentUrl in state.
const [currentUrl, setCurrentUrl] = React.useState(pathname)
React.useEffect(() => {
   setCurrentUrl(pathname)
}, [pathname])

// now you would add the contolled `currentUrl` state to its useEffect deps.
useEffect(() => {
  if (currentUrl === '/dashboard/global') {
    // ..........
  } else if (currentUrl === '/dashboard/my-posts') {
    // ..........
  }
}, [currentUrl]);
like image 63
Muhammad Sammy Avatar answered May 11 '26 13:05

Muhammad Sammy