How to prevent js variables from being reset on reload in Polymer?

887 Views Asked by At

I am trying to build a simple app on polymer using predix, the problem I am facing is: When the page reloads, the variables go back to their initial state, I am using those variables to show/hide content on navigation to other pages(.html files). I have one main .html file, where the variables are declared and has routes to all the files .

Questions:

  1. What are the ways to prevent this?

  2. How can I do this better as I am planning to build another bigger and complex application, which will require users logging in and out?

2

There are 2 best solutions below

3
On BEST ANSWER

Any information you need to store on the client should be written in localStorage. I personally prefer using redux with my state stored in localStorage. With this my users can continue to work exactly where they stopped. Athentication is something else you need to implement a Refresh Token mechanism like Auth0 is providing.

3
On

First of all, why do you need to reload the page or are you asking if for the reason that the user might reload the page? With polymer, it's a single view application, where the page should never reload and instead content is switched inside the current page.

That said, and because you asked for alternatives, you can also use your router to push to window.history and store the updated variables there.

window.history.pushState({'navigate': true, 'url': url, 'extra': extra}, 'FSport', url);

window.history.replaceState({'navigate': true, 'url': url, 'extra': extra}, 'FSport', url);

I don't know how the current router works in Polymer because we had to write our own router because that element didn't exist when we started using Polymer.


If you decide to go with saving in localStorage, also remember that you got indexDb for objects by using localforage. Even though it's slower than localStorage, you also got the benefit of handling promises (asynchronous data fetching).