Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

reactjs - Best way to check if there is already a token in local storage using use effect in React Context

good day. Is this the best way to check if there is already a token in my local storage in my AuthContext? I used a useEffect hook in checking if the token already exists. Should I change the initial state of isAuthenticated since it is always false upon rendering? Im not sure. Thank you

import React, { useState, useContext, useEffect } from "react";

const AuthContext = React.createContext();

export function useAuth() {
    return useContext(AuthContext);
}

export const AuthProvider = ({ children }) => {
    const [isAuthenticated, setAuthenticated] = useState(false);

    const login = () => {
        setAuthenticated(true);
    };

    useEffect(() => {
        const token = localStorage.getItem("AuthToken");
        if (token) {
            setAuthenticated(true);
        } else if (token === null) {
            setAuthenticated(false);
        }

        return () => {};
    }, []);

    return <AuthContext.Provider value={{ isAuthenticated, login }}>{children}</AuthContext.Provider>;
};

question from:https://stackoverflow.com/questions/65952369/best-way-to-check-if-there-is-already-a-token-in-local-storage-using-use-effect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest using a state initializer function so you have correct initial state. You won't need to wait until a subsequent render cycle to have the correct authentication state.

const [isAuthenticated, setAuthenticated] = useState(() => {
  const token = localStorage.getItem("AuthToken");
  return token !== null;
});

The rest can likely remain the same.

I suggest you also provide a default context value as well.

const AuthContext = React.createContext({
  isAuthenticated: false,
  login: () => {},
});

export function useAuth() {
  return useContext(AuthContext);
}

export const AuthProvider = ({ children }) => {
  const [isAuthenticated, setAuthenticated] = useState(() => {
    const token = localStorage.getItem("AuthToken");
    return token !== null;
  });

  const login = () => setAuthenticated(true);
  
  return (
    <AuthContext.Provider value={{ isAuthenticated, login }}>
      {children}
    </AuthContext.Provider>
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...