Damien Begot
Damien Begot

Reputation: 1

Inertia.reload() Laravel Inertia React Project

Is it a good practice to use Inertia.reload() in your laravel project when you want to reload your component after a post request? If you think there is another way that would be better don't hesitate to suggest me.

Front React

    const addToFavorite = async (videogameId: number) => {
        await axios.post(route("favorites.store"), {
            videogame_id: videogameId,
            user_id: currentUserId,
        });
        Inertia.reload();
    };

     <button type="button" onClick={() => addToFavorite(videogame.id)}>
        <StarIcon />
      </button>

Controller

    public function store(FavoriteRequest $request)
    {
        $favorite = Favorites::create($request->all());
        $favorite->save();

        return redirect()->back();
    }

Upvotes: 0

Views: 638

Answers (1)

zlatan
zlatan

Reputation: 4019

In this case, I think it's better to use built-in Inertia.js Manual visits using the router.post method

So your code will look something like this:

import {router} from "@inertiajs/react";

router.post(route("favorites.store"), {
            videogame_id: videogameId,
            user_id: currentUserId,
        }, {
            preserveScroll: true,
            onSuccess: res => {
                console.log('do something on success')
            },
            onError: err => {
                console.log(err)
            }
        })

You can use preserveScroll so you can prevent resetting the scroll position of the document body. This creates a seamless transition on the page.

And since you're already using return redirect()->back(); in your controller, you don't have to manually reload the page.

Upvotes: 0

Related Questions