2

I have following Code in my Context.js:

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

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

export const Context = createContext(INITIAL_STATE);

export const ContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(Reducer, INITIAL_STATE);

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

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

Now I want to use the Context in a class component and especially call the dispatch function, here a minimal example:

export default class Register extends Component {
  static contextType = Context;

  componentDidMount() {
    const { dispatch } = this.context;
    dispatch({ type: "LOGIN_START" });
  }

  render() {
    return (
      <div></div>
    )
  }
}

The Problem now is that dispatch is undefined, when I want to call it inside my class. Before I used the same context with const { dispatch, isFetching } = useContext(Context); inside a functional component and everything worked fine, what is the problem?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375

1 Answers1

2

As suggested in one of the comments above, my ContextProvider has to be an ancestor of my Register component in the component tree. I simply added it inside my index.js:

...
import { ContextProvider } from "./context/Context";

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <ContextProvider>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </ContextProvider>
);