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?

7
  • 1
    What does console.log(this.context) prints? Commented Jan 5, 2023 at 21:26
  • Just the initial state: {user: null, isFetching: false, error: false} Commented Jan 5, 2023 at 21:30
  • 1
    So it seems that your Register is not within ContextProvider Commented Jan 5, 2023 at 21:32
  • Okay, how do I add it there? Commented Jan 5, 2023 at 21:36
  • 1
    See for examples the documentation, where ThemeContext.Provider is a parent of Toolbar (it doesn't have to be a direct parent) Commented Jan 5, 2023 at 21:40

1 Answer 1

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>
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.