2

I am using an Auth Context Provider in my App, which is initialised in this file:

authState.js

import React, { useReducer, createContext, useContext } from "react";
import authReducer from "./authReducer";

const initialState = {
  user: null,
};

const AuthContext = createContext();

export const AuthStateProvider = ({ children }) => {
  const [state, dispatch] = useReducer(authReducer, initialState);

  return (
    <AuthContext.Provider value={[state, dispatch]}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuthContext = () => useContext(AuthContext);

This context is then imported in App.js for getting the user auth details:

App.js

...
...
import { useAuthContext } from './context/auth/authState';
...
...
const [{ user }, authDispatch] = useAuthContext();

I get the error at const [{ user }, authDispatch] = useAuthContext(); line.

eternityparadigm
  • 375
  • 3
  • 10
  • 1
    Maybe I am wrong, but according to the [docs](https://reactjs.org/docs/hooks-reference.html#usecontext) the `useContext` returns only a single value. That is why you can not destruct it with your current logic, the `[{ user }, authDispatch] = useAuthContext();`. This is just a quick idea, with the details you provided. :) Edit: check what you actually pass in with the `useAuthContext`, maybe that would be helpful. – vazsonyidl Apr 28 '22 at 08:24
  • Thanks for responding , but we can actually destructure it this way , cuz I export [{state, dispatch}]. – eternityparadigm Apr 30 '22 at 07:40

1 Answers1

1

I found the solution to this, so I console logged useAuthContext() on @vazsonyidl suggestion and received undefined. So the [state,dispatch] were not known to <App/> component. All I did was to wrap my App component within <AuthStateProvider></AuthStateProvider> and it was resolved. Thanks for the suggestion @vazsonyidl.

eternityparadigm
  • 375
  • 3
  • 10