Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.js : router.push not refreshing the page

I'm building a next.js page /page/data/[dataId] (this page is navigated when A user clicks on a link from page /page/data , I fetch the list of items through an API ).

When user clicks on a button , I call an API to delete this item from DB . Once the API call is successful. I need to redirect user back to /page/data page . Here's how I'm doing it :

 async function removeData(){

    // ... some logic

    await removeData({input});
    setTimeout(()=>{
          router.push("/page/data"); // redirecting to parent
     },2000)

}

Once the user is redirected back to /page/data/ I need to refresh the list of data items bacause I want to remove the item which got deleted. Now the problem is - The /page/data/ is not getting refreshed after navigating it through router.push.

I know we can achieve this by replacing router.push to window.location="/page/data" but that is very expensive way.

I also tried :

router.push("/page/data",undefined,{shallow:false})

but it didn't work.

Anyone can you help me how can we achieve this in optimal way ? I find window.location approach too expensive.

like image 303
programoholic Avatar asked Sep 12 '25 17:09

programoholic


1 Answers

For next.js app router:

MACROSystems' approach didn't work for me, but led me to the right track. The correct approach should change the order of the two lines:

router.push("/page/data")
router.refresh()

What it does:

  1. Navigate back to the redirected page first.
  2. Refetch data from the server and merge it into current page. (Here is the redirected page)

If we call refresh first, then next.js will refetch the page before the redirect. If something only exists on the redirected page and not on the current page, that data might not be updated.

like image 198
Karson Jo Avatar answered Sep 15 '25 09:09

Karson Jo