Home > Back-end >  at nextjs router. how to get path after router push
at nextjs router. how to get path after router push

Time:10-31

I am making a site and this is some part of them. let's say I am in "home" page. and I will go to "service" page.

I want to get path of "service" page. (I want to get like "/service", after "router push".

but my code show "/" (before "router push"'s path)

How to get present path after "router push", not previous path?

thanks.

import Link from 'next/link'
import { useRouter } from "next/router"

const SideBar = (props) => {
  const router = useRouter()
  const handleClick = (e, path) => {
    e.preventDefault()
    props.toggleMenu()
    router.push(path)
    console.log( router.pathname ) // this shows path "before router push"    
  }
 return (
    <div className="sidebar">
       <Link href="/">
         <a onClick={(e)=> handleClick(e, "/")} >HOME</a>
       </Link>
       <Link href="/service">
         <a onClick={(e)=> handleClick(e, "/service")} >SERVICE</a>
       </Link>
    </div>
 )
}
export default SideBar

CodePudding user response:

Use router.pathname to get the current path. router.asPath to get the current path with query.

Lets say your url is http://localhost:3000/service?serviceId=1

const router = useRouter();

console.log(router.pathname); // returns /service
console.log(router.asPath); //returns /service?serviceId=1

CodePudding user response:

By the time that console.log is triggered, you haven't navigated to the new route yet.

If you want to console.log AFTER you've routed, you need to set up a function to trigger after the route has changed.

In that case, you need to set up an "on" event listener in your _app.js file:

router.events.on('routeChangeComplete', () => console.log(router.pathname))
  • Related