I’ve been using InertiaJS on all my new projects, and it’s been a great choice so far. But as it happens with everything in the world, there have been a few hiccups.

One of those hiccups has to do with refreshing state when navigating back. Inertia is designed to mimic the default browser behavior, which is to show the previous state when navigating history. The problem is, sometimes, most of the time, you do want to show the actual, present state your data, even if you navigate back.

Consider the following example where I’m clicking an e-mail, marking it as read (color changes, inbox counter goes down by one), and then when I navigate back, the inbox shows the previous state.

Browsing back shows the previous state, which is nice, but not always the desired behavior.

Solution

The simplest solution I was able to come up with is to listen to the popstate browser event and trigger an inertia reload request to refresh the state. The popstate event is dispatched every time the active history entry changes between two history entries for the same document.

I place the following listener in the main JavaScript file where the Inertia app is initialized:

//app.js
mounted() {
  window.addEventListener('popstate', () => {
    this.$inertia.reload({preserveScroll: true, preserveState: false})
  })
}