When navigating browser history, Inertia restores pages using prop data cached in history state. Inertia does not, however, restore local page component state, since this is beyond its reach. This can lead to outdated pages in your browser history.
For example, if a user partially completes a form, then navigates away, and then returns back, the form will be reset and their work will be lost.
To mitigate this issue, you can tell Inertia which local component state to save in the browser history.
To save local component state to the history state, use the remember
feature to tell Inertia which data it should remember.
import { useRemember } from '@inertiajs/inertia-vue3'
export default {
setup() {
const form = useRemember({
first_name: null,
last_name: null,
})
return { form }
},
}
Now, whenever your local form
state changes, Inertia will automatically save this data to the history state, and restore it on history navigation.
If your page contains multiple components that use the remember functionality, you need to provide a unique key for each component, so that Inertia knows which data to restore to each component.
import { useRemember } from '@inertiajs/inertia-vue3'
export default {
setup() {
const form = useRemember({
first_name: null,
last_name: null,
}, 'Users/Create')
return { form }
},
}
If you have multiple instances of the same component on the page using the remember functionality, be sure to also include a unique key for each component instance.
import { useRemember } from '@inertiajs/inertia-vue3'
export default {
setup({ user }) {
const form = useRemember({
first_name: null,
last_name: null,
}, `Users/Edit:${user.id}`)
return { form }
},
}
If you're using the form helper, you can pass a unique form key as the first argument when instantiating your form, and this will cause the form data and errors to automatically be remembered.
import { useForm } from '@inertiajs/inertia-vue3'
const form = useForm('CreateUser', data)
const form = useForm(`EditUser:${user.id}`, data)
The remember
property in Vue 2, and the useRemember
hook in Vue 3, React and Svelte all watch for data changes, and automatically save those changes to the history state, and then restore it on page load.
However, it's possible to also manage this manually using the underlying remember()
and restore()
methods in Inertia.
import { Inertia } from '@inertiajs/inertia'
// Save local component state to history state
Inertia.remember(data, 'my-key')
// Restore local component state from history state
let data = Inertia.restore('my-key')