vincent15000's avatar

How does the optimistic updates work ?

Hello,

I'm trying to use the optimistic updates with InertiaJS v3.

https://inertiajs.com/docs/v3/the-basics/optimistic-updates#form-helper

const save = async () => {
    form.optimistic((props) => ({ category: props.category, name: form.name })).put(route('admin.categories.update', { category: props.category }));

    editMode.value = false;
    updated.value = true;
};

The updated name is displayed on the screen, but its because the page is reloaded.

But I don't want any reload.

public function update(Request $request, Category $category)
{
    $category->fill($request->all());

    $category->save();
}

Hmmm ... can someboby explain how I can use the optimistic updates properly ?

Thanks for your help.

V

0 likes
3 replies
imranbru's avatar

Hey Vincent,

You're missing a return statement in your controller. Inertia requires a redirect after a mutation (POST/PUT/PATCH/DELETE) so it can fetch the fresh page props under the hood.

public function update(Request $request, Category $category)
{
    $category->fill($request->all());
    $category->save();

    return back(); // <-- You need this
}
1 like
vincent15000's avatar

I don't understand how this works.

form.optimistic((props) => ({ category: props.category, name: form.name })).put(route('admin.categories.update', { category: props.category }));

Can you explain me please ?

form.optimistic((props) => ({
  contacts: /* updated */
})).post(url);

The ```/* updated */ part is the confirmation from the backend with updated datas ? Or is it the frontend changes done by the user ?

vincent15000's avatar

Ok just found, the /* updated */ part is the user input, then waiting for confirmation by the backend.

Please or to participate in this conversation.