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.
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With