简体   繁体   中英

React Firebase - User is logged out after every page refresh

I have created Firebase Authentication with ReactJS .
Everything works fine until The page refreshes. I'm using onAuthStateChanged listener, however, after I'm refreshing the page, it navigates me back to the Login form.

UserAuthContext.js

const userAuthContext = createContext();

export function UserAuthContextProvider({ children }) {

    const [user, setUser] = useState("");

    function signUp(email, password, username) {
        return createUserWithEmailAndPassword(auth, email, password);
    };

    function logIn(email, password) {
        return signInWithEmailAndPassword(auth, email, password);
    };

    function logout() {
        return signOut(auth);
    }

    useEffect(() => {
        const subscribe = onAuthStateChanged(auth, (currentUser) => {
            setUser(currentUser);
        });
        return subscribe;
    }, []);

    return (
        <userAuthContext.Provider value={{ user, signUp, logIn, logout }}>
            {children}
        </userAuthContext.Provider>
    );
}

export function useUserAuth() {
    return useContext(userAuthContext);
}

动图

You are saving the the user to a react state hook. React state does not persist data after page reload. A common way people persist data is by saving it into local storage or a cookie. However, these methods are prone to attacks like XSS and CSRF.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM