Do a client side reload and change url in Next.js

2.3k views Asked by At

I have the following code snippet in one of my Next js components -:

import { useRouter } from "next/router";
import Router from "next/router";
import { Menu } from "antd";
export default function AccountMenuList() {
  const router = useRouter();
  function onClick({ key }) {
    switch (key) {
      case "my-account":
        router.push("/profile");
        break;
      case "my-wishlist":
        router.push("/wishlist");
        break;
      case "logout": {
        localStorage.removeItem("user");
        // Router.reload(window.location.pathname);
        router.reload();
        break;
      }
      default:
        break;
    }
  }
  return (
    <Menu onClick={onClick}>
      <Menu.Item key="my-account">MY ACCOUNT</Menu.Item>
      <Menu.Item key="my-wishlist">MY WISHLIST</Menu.Item>
      <Menu.Item key="logout">LOGOUT</Menu.Item>
    </Menu>
  );
}

In the app, I am on the '/profile' page and then I click on logout button. What I want to do is to do a url change back to the home page '/' and do a client side reload as well. I know that a client side reload can be done with router.reload(). But using it with router.push() does not change the url and the page itself.

Can anyone explain what I must be doing or thinking wrong?

1

There are 1 answers

0
Hussein Duvigneau On

In this case I would do a hard window.location="/" (or explicitly set your base URL instead of the slash). It will send the browser to that URL and reload the page as it does so.