#Using the back button of the browser does not trigger a re-fetch of the props from the backend

1 messages · Page 1 of 1 (latest)

sudden yew
#

I've seen some threads about this on github but I still have no idea how to resolve it or if it could be resolved at all. So in my laravel backend I have a simple controller method that gets all of the user's favorite listings like so :

    public function viewFavorites(Request $request)
    {

        $user = $request->user();

        $favoriteListings = $user->favoriteListings()->withFullDetails()->get();
        $favoriteListings = $favoriteListings->map(function ($listing) {
            $listing->is_favorited = true;
            return $listing;
        });

        return Inertia::render('FavoriteListings', [
            'listings' => Inertia::render($favoriteListings)
        ]);
    }

So far nothing complex. Then in my frontend react component I place those listings in a state, I map them out and I have a button that sents a request to the backend to toggle the favorite status ( if a listing is already favorited it removes it from favorites and vice versa) and then it updates the state with the new favorite status so that the information can be re-rendered live. So far so good. Everything is working fine EXCEPT when I navigate away to another page, let's say the home page, and then I click the browser's back button I get greeted with the initial state BEFORE making any changes (like removing a favorite listing). The only fix for this is refreshing the page, or clicking a link that leads to the page. But the back button for some reason does not trigger a refetch of the listings from the controller, instead it gets them from some presumably cached source. Is this fixable at all and if so how?

sudden yew
#

Update: I made a custom hook:

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

export function useForceReloadOnNavigation() {
    useEffect(() => {
        const handlePopState = () => {
            router.reload({ only: ["listings"] });
        };

        window.addEventListener("popstate", handlePopState);

        return () => {
            window.removeEventListener("popstate", handlePopState);
        };
    }, []);
}
``` and I call it on the pages that I need fresh data from whenever the user navigates back and forth. It's just 2 of the pages (so far). I don't know if this solution has negative consequences but that's all I could figure out for now
indigo walrus
dense bluff