One possible solution is to make sure that the component being rendered by Inertia has the necessary props to preserve state and scroll. Inertia provides two props for this: initialData and remember.
initialData is used to pass initial data to the component, including the current search value. remember is used to tell Inertia to remember the current state of the component, including scroll position.
Here's an example of how to use these props:
// In the controller method that returns the Inertia response
return Inertia::render('Friends/Index', [
'friends' => $friends,
'search' => $search,
'remember' => true, // Tell Inertia to remember the component state
]);
// In the Vue component
<template>
<div>
<input type="text" v-model="search" @input="updateSearch" />
<ul>
<li v-for="friend in friends" :key="friend.id">{{ friend.name }}</li>
</ul>
</div>
</template>
<script>
export default {
props: {
initialData: {
type: Object,
required: true,
},
remember: {
type: Boolean,
default: false,
},
},
data() {
return {
friends: this.initialData.friends,
search: this.initialData.search,
};
},
methods: {
updateSearch() {
this.$inertia.get(route('friends.index', { search: this.search }), {
preserveState: true,
preserveScroll: true,
});
},
},
mounted() {
if (this.remember) {
this.$inertia.remember({ data: ['friends', 'search'] });
}
},
};
</script>
In this example, the Friends/Index component receives the search value and friends data as props from the controller. The component uses these props to initialize its data and render the search results.
The updateSearch method is called whenever the search input changes. It uses this.$inertia.get to fetch the search results from the server, passing preserveState and preserveScroll to preserve the component state.
Finally, the mounted hook is used to tell Inertia to remember the friends and search data if remember is set to true. This ensures that the component state is preserved across page loads.