Inertia.JS reload props after post request

Viewed 8438

I am currently pretty confused why Inertia.js is not reloading or rerendering my page.

I have a form that could be filled, once submitting this will execute:

Inertia.post("/ban", ban);

This will redirect to a POST in the web.php of my Laravel. That looks like this:

Route::post("/ban", [Speler::class, "ban"]);

This redirects to a class called "Speler", in there is a function called "ban". Once done some SQL statements it will execute this return:

return Redirect::route("speler", [$steam])->with("success", "Ban doorgevoerd!");

This will go back to the web.php, and go to the route speler with the session data "success". That redirect goes into the web.php:

Route::get("/speler/{steam}", [PageLoader::class, "speler"])->name("speler");

This one goes to the PageLoader controller, and execute the "speler" function.

But here it gets weird, this will return a Inertia::render of the same page the person was on, but would need to add another prop, or change the prop. (so i can show a popup with te text that it succeeded)

return Inertia::render("Panel/Speler",
                ["steamNaam" => $steamNaam, "discord" => $discord, "karakterAantal" => $karakterAantal, "karakters" => $karakters, "sancties" => $sanctiesReturn, "punten" => $aantalPunten, "steamid" => $steamid, "success" => $melding]
            );

The "success" prop contains $melding that simply contains a string.

But for some reason it doesn't seem to re-render the page, the form stays filled, and the props are the same. Does someone have a solution?

1 Answers

If you setup your form with the form helper, you can reset the form on a successful post like this:

form.post('/ban', {
  preserveScroll: true,
  onSuccess: () => form.reset(), // reset form if everything went OK
})

The success message, which you set with

return Redirect::route("speler", [$steam])->with("success", "Ban doorgevoerd!");

is usually taken care of by the Inertia middleware and made available as 'Shared data'. See this docs page on how to configure that. Shared data is rendered in $page.props variable. That is where you can find the Ban doorgevoerd! message. You can show these to the user as follows:

<div v-if="$page.props.flash.message" class="alert">
    {{ $page.props.flash.message }}
</div>

Depending on your implementation, you would need to watch this property. See the FlashMessages component on the pingCRM demo app for an example implementation.

Related