'Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null when calling set function

I'm trying to set up a user login system using the userContext and localSotrage of the browser.

I have a first file that includes my provider and my context: Auth.jsx

import { hasAuthenticated } from '../services/AuthAPI';

export const AuthContext = createContext()

const AuthProvider = ({children}) => {
    const [auth, setAuth] = useState(hasAuthenticated());
    const value = useMemo(() => ({auth, setAuth}, [auth, setAuth]));


    return (
        <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
    )

    
}

export default AuthProvider

export const AuthState = () => {
    return useContext(AuthContext)
  }

I also have a page that allows to manage elements of the LocalStorage and to know if a user is already connected (it for now hardcoded): AuthAPI.jsx


export function hasAuthenticated() {
    const token = getItem('sessionToken');
    const result = token ? tokenIsValid(token) : false;

    if (false === result) {
        removeItem('sessionToken');
    }

    return result;
}

export function login(credentials) {
    addItem('sessionToken', 'tokenSample');
    return true;
};

export function logout() {
    removeItem('sessionToken');
}

function tokenIsValid(token) {
    // const { exp: expiration } = jwtDecode(token);

    // if (expiration * 1000 > new Date().getTime()) {
    //     return true;
    // }

    return true;
}

And finally I have my connection page which must update the auth variable using the context: Login.jsx

import { useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/Auth';
import { login } from '../services/AuthAPI';

const Login = () => {
  const navigate = useNavigate();
  const {auth, setAuth} = useContext(AuthContext);

  const [user, setUser] = useState({
    username: "",
    password: ""
  })

  const handleChange = ({ currentTarget }) => {
    const { name, value } = currentTarget;

    setUser({ ...user, [name]: value })
  }

  async function handleSubmit(event) {
    event.preventDefault();

    try {
      const response = await login(user);
      setAuth(response);
      navigate('news', { replace: true });
      console.log('oui');
    } catch (e) {
      console.error(e);
    }
  }

  useEffect(() => {
    if (auth) {
      navigate('news', { replace: true });
    }
  }, [navigate, auth]);

  return (
    <div className="container border rounder mt-5 p-3 bg-light">
      <form className="form-profile" onSubmit={setAuth(true)} >
        <fieldset>
          <legend>Se connecter</legend>
          <div className="form-group">
            <label htmlFor="email">Email</label>
            <input
              type="text"
              name="username"
              className="form-control"
              id="email"
              placeholder="[email protected]"
              onChange={handleChange}
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">Password</label>
            <input
              type="password"
              name="password"
              className="form-control"
              id="password"
              placeholder="Password"
              onChange={handleChange}
            />
          </div>

          <button type="submit" className="btn btn-outline-primary">
            Se connecter
          </button>
        </fieldset>
      </form>
    </div>
  );
};

export default Login;

But React returns this error: Uncaught TypeError: react__WEBPACK_IMPORTED_MODULE_0__.useContext(...) is null site:stackoverflow.com at line setAuth(response); from Login.jsx

Do you have any idea ?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source