-1

I'm trying to useContext on the file app.js but I receive an error:

_React$useContext is undefined

Normally, I wrap correctly the only component I have, but it tells it's undefined (I saw few answers before asking, some of them tells it's because of wrap problem). How should I approach the error?

import React from "react";
import "./App.css";
import UserProfile from "./components/UserProfile";
import UserContextProvider from "./contexts/UserContext";

// create method toggleStatus that will change the
// status value from true to false. keep in mind that this method has
//to be created before our state!

  // create 2 properties for state: status (boolean)
  //and toggle (toggleStatus method previously created)

  // pass the whole state to the provider as a value

  function App() {
    function toggleStatus() {
      updateUserValue(!userValue);
    }
    return (
      <UserContextProvider>
        <UserProfile />
      </UserContextProvider>
    );
  }
};
export default App;

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Bpio
  • 23
  • 4

1 Answers1

0

In your example you're trying to access the context outside of the provider.

All context consumers must be a descendant of a provider. Look at this example: https://codesandbox.io/s/heuristic-hamilton-mfppv?file=/src/App.js

In short, your useContext must be used in a component that is a descendant of your UserContextProvider.

I usually create a custom hook on top of useContext for my contexts that can help you find these errors:

function useMyContext() {
  const context = React.useContext(MyContext);
  if (!context) {
    throw new Error('useMyContext must be used within a MyContextProvider');
  }
  return context;
}
Phillip
  • 6,033
  • 3
  • 24
  • 34