skip to Main Content

I have tried to use useEffect to store user details in local storage but unable. Please do any help on it.

Full Code :


const AuthContext = createContext()

const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null); 

  useEffect(() =>{
    const storedUser = JSON.parse(localStorage.getItem('user'))
    setUser(storedUser)
  },[])

  const login = (userData) => {
    localStorage.setItem('user', JSON.stringify(userData));
    setUser(userData);
  };

  const getUser = () => {
    return JSON.parse(localStorage.getItem("user"))
  }

2

Answers


  1. Could you provide full code AuthProvider component? It seems issue in passing values in AuthContext.Provider, but I don’t see this part

    Login or Signup to reply.
  2. const AuthContext = createContext()

    const AuthProvider = ({ children }) => {
    const [user, setUser] = useState(null);

    useEffect(() =>{
    const storedUser = JSON.parse(localStorage.getItem(${user}))
    setUser(storedUser)
    },[])

    const login = (userData) => {
    localStorage.setItem(${user}, JSON.stringify(userData));
    setUser(userData);
    };

    const getUser = () => {
    return JSON.parse(localStorage.getItem(${user}))
    }

    Are you trying to reference the variable? I think you need string interpolation for your "user". I changed it for you in the code above thinking it should work if you’re trying to reach that variable. String interpolation is what I normally use when trying to put a variable inside a string using proper syntax ${varName} inside a ` (it’s esc key on the keyboard also known as backticks or grave accents) quotation marks for this to work. It will not work with the other quotation marks, but only that one.

    I hope this works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search