Search code examples
node.jsreactjsauthenticationlocal-storagereact-context

User not showing in local storage


I was working on my first MERN project and was trying to use local storage with context API, but the data is not getting reflected in the local storage and no error is getting reflected either in the console.

When I log in as a user, the local storage still stays empty.

Below is my Context.js code

 import { createContext, useEffect, useReducer, useState } from "react";
 import Reducer from "./Reducer";



const INITIAL_STATE = {
user: JSON.parse(localStorage.getItem("user")) || null,
isFetching: false,
error: false,
};

 export const Context = createContext(INITIAL_STATE);

 export const ContextProvider = ({ children }) => {
 const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

 const [user, setItems] = useState([]);

 useEffect(() => {
 localStorage.setItem('user', JSON.stringify(state.user));
}, [state.user]);

 return (
<Context.Provider
  value={{
    user: state.user,
    isFetching: state.isFetching,
    error: state.error,
    dispatch,
  }}
>
  {children}
</Context.Provider>
 );
};

Below is my login.jsx code

 import { Link } from "react-router-dom";
 import "./login.css"
 import { useContext, useRef } from "react";
 import axios from "axios";
 import { Context } from "../../../context/Context";

  export default function Login() {

  const userRef = useRef();
  const passwordRef = useRef();
  const { user, dispatch, isFetching } = useContext(Context);


 const handleSubmit = async (e) => {
  e.preventDefault();
  dispatch({ type: "LOGIN_START" });
   try {
    const res = await axios.post("/auth/login", {
    username: userRef.current.value,
    password: passwordRef.current.value,
     });
     dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
    } catch (err) {
  dispatch({ type: "LOGIN_FAILURE" });
    }
 };

 console.log(isFetching)

  return (
   <div className="login">
    <span className="loginTitle">Login</span>
    <form className="loginForm" onSubmit={handleSubmit}>
    <label>Username</label>
    <input className="loginInput" type="text" placeholder="Enter your username..." ref= 
   {userRef} />
      <label>Password</label>
       <input className="loginInput" type="password" placeholder="Enter your 
    password..." 
      ref={passwordRef} />
       <button className="loginButton" type="submit">Login</button>
      </form>
       <button className="loginRegisterButton">
       <Link className="link" to="/register">Register</Link>
      </button>
    </div>
   );
 }

I have tried googling it out for 2 hours straight, but am not able to get the mistake from which it is arising. Any help is highly appreciated!!


Solution

  • import { createContext, useEffect, useReducer, useState } from "react";
     import Reducer from "./Reducer";
    
    
    
    const INITIAL_STATE = {
    user: JSON.parse(localStorage.getItem("user")) || null,
    isFetching: false,
    error: false,
    };
    
     export const Context = createContext(INITIAL_STATE);
    
     export const ContextProvider = ({ children }) => {
     const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);
    
     const [user, setItems] = useState([]);
    
     useEffect(() => {
     console.log(state.user);
     localStorage.setItem('user', JSON.stringify(state.user));
    }, [state.user]);
    
     return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
     );
    };

    I think you'd better check first if user data is in there.