Next.js Discord

Discord Forum

Proper way to update a page after route.push() following a POST request ?

Answered
Persian posted this in #help-forum
Open in Discord
PersianOP
I have a basic example where I'm working with two pages, one page (addnames) is just an entry page where you submit names and they get sent to the server. The second page (viewnames) will pull the list of names from the server as a list and show them.

In my first page I have a client component where I use a form and on the submit there is an async function that handles the POST request, once status == 201 I use router.push("/viewnames"); However, I've noticed that the data isn't always up to date and if I do a manual refresh it is.

On page two (viewnames) for the GET request I do have revalidate: 0 as well under the next: { } object.

The only thing I noticed is if I do:

router.push("/viewnames");
router.refresh();

It will work fine. The guide I was reading always seems to use the refresh before the push, but I run into the same problem. Since my first page is a client component I cannot use revalidatePath, so I'm not sure if the above push then refresh is correct? I supposed I could make a server component and pass it into my client one with this action. Also is there a correct order for push and refresh?

Thank you.
Answered by Persian
Okay, got it working.

"use server"

import { revalidatePath } from "next/cache";

function ServerRevalidate(url) {
    revalidatePath(url);
}

export default ServerRevalidate;


Then I just use it before my push request.

ServerRevalidate("viewnames");
View full answer

6 Replies

What you can do is make a server action which will take in an id or page name and revalidate accordingly. Since a server action is a mutation you can also just do your updates on it.
@Persian
router.refresh is a pretty hacky solution
@Arinji What you can do is make a server action which will take in an id or page name and revalidate accordingly. Since a server action is a mutation you can also just do your updates on it.
PersianOP
Since page one is a client component and page two is all server generated, would I just make a server component that uses revalidatePath and include it into my first page ( the client component ) ?
Thank again for the help.
PersianOP
Okay, got it working.

"use server"

import { revalidatePath } from "next/cache";

function ServerRevalidate(url) {
    revalidatePath(url);
}

export default ServerRevalidate;


Then I just use it before my push request.

ServerRevalidate("viewnames");
Answer