laravelvue.jsinertiajs

Laravel VILT Stack, Inertia Shared Data


I'm working on my first VILT stack project, a T-shirt store where customers can add items to a cart. The cart is stored in the session and shared with the frontend using the HandleInertiaRequests middleware, like this:

public function share(Request $request): array
{
    $cart = session()->get('cart', []);
    return [parent::share($request), 'cart' => $cart];
}

I have a reusable cart component that displays the current number of items in the cart, and it's working as expected when navigating normally. Here's the cart component:

<script setup>
import { Link } from "@inertiajs/vue3";
import Cart from "@/Icons/Cart.vue";
import { computed } from "vue";
import { usePage } from "@inertiajs/vue3";

const page = usePage();
const cartCount = computed(() => page.props.cart.length);
</script>

<template>
    <Link :href="route('cart')" >
        <Cart />
        <div>
            <p>{{ cartCount }}</p>
        </div>
    </Link>
</template>

The issue is that when a user adds an item to the cart and then uses the browser's back button to navigate to the previous page, the cart count displayed in the component shows stale data. If I refresh the page, the correct count is displayed.

From my understanding, this happens because the browser caches the previous page, and the page.props.cart data doesn't update unless the page is reloaded.


Solution

  • You could leverage Inertia's partial reloads in tandem with the navigate event to work around this issue. Something like the following might work:

    import { router } from '@inertiajs/vue3'
    
    // Listen for navigation through history
    router.on('navigate', () => {
      // Reload only the props required
      router.reload({ only: ['cart'] });
    });