My app uses the Firebase API for User Authentication, saving the Login status as a boolean value in a Vuex State.
When the user logs in I set the login status and conditionally display the Login/Logout button accordingly.
But when the page is refreshed, the state of the vue app is lost and reset to default
This causes a problem as even when the user is logged in and the page is refreshed the login status is set back to false and the login button is displayed instead of logout button even though the user stays logged in....
What shall I do to prevent this behavior
Shall i use cookies Or any other better solution is available...
-
-
This is a known use case. There are different solutions.
For example, one can use
vuex-persistedstate
. This is a plugin forvuex
to handle and store state between page refreshes.Sample code:
What we do here is simple:
js-cookie
getState
we try to load saved state fromCookies
setState
we save our state toCookies
Docs and installation instructions: https://www.npmjs.com/package/vuex-persistedstate
I think use cookies/localStorage to save login status might cause some error in some situation.
Firebase already record login information at localStorage for us include expirationTime and refreshToken.
Therefore I will use Vue created hook and Firebase api to check login status.
If token was expired, the api will refresh token for us.
So we can make sure the login status display in our app is equal to Firebase.
I've solved this by resetting my headers every time I re-load also fetch user data, I don't know what is better ...
put on state:
put on mutations:
works fine for me!
When creating your VueX state, save it to session state. In this way, the information will be lost when the browser is closed. Avoid use of cookies as these values will travel between client and server.
Use
sessionStorage.clear();
when user logs out manually.