John Moore
John Moore

Reputation: 7129

Vuex, vue-router and handling page reload (F5)

I'm in the process of switching over the application I'm building to be a single-page application, using vue-router and vuex. But this is my first SPA, so I'm falling foul of some newbie issues. I had things working as I wanted, with my product listing and edit modes, successfully routed via /product/list and /product/edit, and then I discovered that (unsurprisingly) things broke for the edit mode when I reloaded the page using F5 (or Ctrl-F5). The edit mode is dependent on the state having been set up in the list mode and after a reload this has not occurred.

So my question is a general, architectural one. What is the best way to do this kind of thing? Should I try to persist the Vuex state to local or session storage, so that it can survive a reload? Or should I ensure that the state is able to be regenerated using information in the route URL (which I'm not doing at the moment)? That is, instead of having the URL as /product/list, I should have /product/list?search=whatever&order=field, so that on reload the search and sort can be executed again. Similarly, instead of /product/edit, I'd have /product/edit?id=12345, so that if the page were refreshed, the specific product could be loaded again.

My preference would be to persist state to localStorage (I don't have to contend with browsers which don't have storage). But I'm wondering whether I'm approaching SPA design in the wrong way, I should still be thinking of it in REST terms, even if it's all taking place within the one page.

Upvotes: 4

Views: 4440

Answers (2)

Sergio J. Batarce
Sergio J. Batarce

Reputation: 84

For me, what worked perfectly was:

const router = new Router ({

   // mode: "history",

   history: true,

   hashbang: false,

   root: "/your app directory",

   base: "",

      ...
      ...

Upvotes: 2

Justin
Justin

Reputation: 2970

I've handled this by keeping the ID present in URL and then refetching data on reload. Sure you could persist to local storage but what happens when someone sends that URL to another user? Or bookmarks it and then clears their browser cache? Most users would expect to be able to go back to the page they were on.

Upvotes: 1

Related Questions