Home > Software engineering >  React contextAPI fetch not updating state
React contextAPI fetch not updating state

Time:09-29

I'm using contextAPI and trying to fetch data and update state using action and reducer, but the state is not getting updated

im using fetch inside useEffect and after fetch i dispatch type GET_EMPLOYEES

AuthContext.js

import AuthReducer from "./AuthReducer";

const initialState = {

  user: JSON.parse(localStorage.getItem("user")) || null,
  employees: [],
  isLoading: false,
  darken: false,
};

const AuthContext = React.createContext(initialState);

export const AuthProvider = ({ children }) => {

  const [state, dispatch] = useReducer(AuthReducer, initialState);

  useEffect(() => {
    const getEmployees = async () => {
      const response = await fetch("http://localhost:8000/get-employees");
      const data = await response.json();
      dispatch({ type: "GET_EMPLOYEES", payload: data });
    };
    getEmployees();
  }, []);
}

i made reducer to update state, in case of GET_EMPLOYEES, it should return state as is but update employees with action payload.

AuthReducer.js


const AuthReducer = (state, action) => {

  switch (action.type) {
       case "LOGIN":
      return {
        user: null,
        isLoading: true,
      };

    case "LOGIN_SUCCESS":
      return {
        user: action.payload,
        isLoading: false,
      };
    case "GET_EMPLOYEES":
      return { ...state, employees: action.payload };
    default:
      return state;
  }
};

i made action type GET_EMPLOYEES, and in case of dispatched, it sends back payload

AuthAction.js

export const login = () => ({
  type: "LOGIN",
});

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

export const getEmployees = (employees) => ({
  type:"GET_EMPLOYEES",
  payload: employees
});

finally trying to access employees state from AuthContext using useContext

RequestVacation.jsx

import AuthContext from "../../../context/AuthContext";

function RequestVacationForm() {

  const { employees } = useContext(AuthContext);

  console.log(isLoading); // false
  console.log(employees); // undefined

}


what is the problem ?

CodePudding user response:

You provider must return something

export const AuthProvider = ({ children }) => {

  const [state, dispatch] = useReducer(AuthReducer, initialState);

  useEffect(() => {
    const getEmployees = async () => {
      const response = await fetch("http://localhost:8000/get-employees");
      const data = await response.json();
      dispatch({ type: "GET_EMPLOYEES", payload: data });
    };
    getEmployees();
  }, []);
}

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

Other than that it works fine https://codesandbox.io/s/billowing-bash-qenf4h?file=/src/App.js

  • Related