How can you persist a logged-in user with firebase?

烂漫一生 提交于 2020-12-13 07:11:52

问题


Thanks a bunch for reading this newbie's question.

So, there is a ReactJS app which is using firebase for its authentication.

Everytime the page is refreshed, the user is gone forever until you login in with the redirected login page.

What have been done so far?

Well, after plodding through all the possible Stackoverflows flowing flawless answers, following have been done:

  1. Implemented the onAuthStateChanged() function like as it appears below:

  firebase.auth().onAuthStateChanged((user) => {
            if (user) {
                console.log('user is logged in');
            } else {
                console.log('user is logged out now')
            }
        });
  1. Set the persistence, which seems to be a silent worker, as follows:

 firebase.auth().setPersistence(firebase.auth.Auth.Persistence.NONE)
        .then(function () {
          console.log("successfully set the persistence");
    
        })
        .catch(function (error) {
          console.log("failed to ser persistence: " + error.message)
        });

Every page reloads logs the user out just like that. Gone!. Nothing. Not even a trace of its dust!

To have a better understanding of this crippling code, I can give you the following screenshots of the console messages.

You get this when you logged in

And the following when the page is refreshed.

Why do you think this error pops up even after applying the above?

Thanks again!

Update1: Took down the setPersistence thing. And it turns out that the user is logged in even after page reloads to the login.

Update 2: User is actually get pulled out when refreshing the page. Now that's what we need to solve here. What do you guys think?


回答1:


The Firebase Auth SDK enables persistence by default. If you want that default behavior, don't call firebase.auth().setPersistence() at all. Just use onAuthStateChanged to know when the persisted user object is first available.



来源:https://stackoverflow.com/questions/65165336/how-can-you-persist-a-logged-in-user-with-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!