0

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();
    }

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.