2 years ago

#75752

test-img

Rihab sabri

Context Api : My Dispateched action is not returning the state

I m trying to log in a user and get his credentials in a state, I m using Context api for the first time but I keep getting an error of user is not defined when i try to log it just to see if I am updating the state. I noticed that the state is not updating.

context.js :

import { createContext, useReducer } from "react";
import Reducer from "./Reducer";
const INITIAL_STATE = {
  user: null,
  isFetching: false,
  error: false,
};

export const Context = createContext(INITIAL_STATE);

export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);
  return (
    <Context.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </Context.Provider>
  );
};

Actions.js:

export const loginStart = (userCredentials) => ({
  type: "LOGIN_START",
});

export const loginSuccess = (user) => ({
  type: "LOGIN_SUCCESS",
  payload: user,
});

export const loginFail = () => ({
  type: "LOGIN_FAIL",
});

Reducer.js:

const Reducer = (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_FAIL":
      return {
        user: null,
        isFetching: false,
        error: true,
      };
    default:
      return state;
  }
};

export default Reducer;

My login function :

  const { dispatch, isFetching } = useContext(Context);
  const [error, setError] = useState(false);

  const submitHandler = async (e) => {
    setError(false);
    e.preventDefault();
    dispatch({ type: "LOGIN_START" });
    try {
      const res = await axios.post("http://localhost:5000/auth/login", values);
      dispatch({ type: "LOGIN_SUCCESS", payload: res.data });
      console.log(res.data);
      //res.data && window.location.replace("/");
    } catch (err) {
      dispatch({ type: "LOGIN_FAIL" });
      console.log(error);
      setError(true);
    }
  };
  console.log(user);  //HERE I GET USER NOT DEFINED ERROR
index.js:

import { ContextProvider } from "./context/Context";
ReactDOM.render(
  <ContextProvider>
    <Router>
      <App />
    </Router>
  </ContextProvider>,
  document.getElementById("root")
);

reactjs

react-context

0 Answers

Your Answer

Accepted video resources