'useContext gives App.js:24 Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

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.



Solution 1:[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.

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 eternityparadigm