Home > Enterprise >  dispatch function is undefiened while using useContext
dispatch function is undefiened while using useContext

Time:07-11

I have created a login system in react and to store user info I am using react context API I have an auth context provider file where I have kept all the state and state providers and I have created another file AuthReducer which has the reducer and AuthAction which contains the actions of the reducers.

I have also created a file that has a function named loginCall to call the dispatch function. and I am using this function in my react component to call the dispatch function but when I call loginCall I am getting dispatch is not function error other values from the context provider are correct just the dispatch function is coming undefined.

please if anyone have any fix let me know

my authContext

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

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

export const AuthContext = createContext(INITIAL_STATE);
export const AuthContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);

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

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

my loginCall function is separate file

import axios from "axios";

export const loginCall = async (userCredential, dispatch) => {
  dispatch({ type: "LOGIN_START" });
  try {
    const res = await axios.post("/auth/login", userCredential);
    dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
  } catch (err) {
    dispatch({ type: "LOGIN_FAILURE", payload: err });
  }
};

any the react component where I am using this loginCall and dispatch function

export default function Login() {
  const email = useRef();
  const password = useRef();
  const { user, isFetching, error, dispatch } = useContext(AuthContext);

  const handleClick = (e) => {
    e.preventDefault();
    console.log({ user, isFetching, error, dispatch });
    dispatch({ type: "LOGIN_START" });
    

    e.preventDefault();
    loginCall(
      { email: email.current.value, password: password.current.value },
      dispatch
    );
  };
 return(
            <>
              .....
            //normal component 
            </>
)

when I console log the { user, isFetching, error, dispatch } I get dispatch: undefined, error: false, isFetching: false, user: null

the other values are correct the dispatch function is coming null.

AuthReducer

const AuthReducer = (state, action) => {
  switch (action.type) {
    case "LOGIN_START":
      return {
        user: null,
        isFetching: true,
        error: false,
      };
    case "LOGIN_SUCCESS":
      return {
        user: action.payload,
        isFetching: false,
        error: false,
      };
    case "LOGIN_FAILURE":
      return {
        user: null,
        isFetching: false,
        error: true,
      };
   }
}

CodePudding user response:

<AuthContextProvider> was not provided in index.js

CodePudding user response:

You need to add this code in index.js

<AuthContextProvider>
  <App />
</AuthContextProvider>
  • Related