Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React context is undefined when i call it in useContext()

I am trying to build a simple authentication system where the logged-in user’s username get saved in local storage. But I also want to save it in a state because pages will be rendered differently according to whether the user is logged in or not.

What I am trying to do is I have in my app.js a loggedUser state. I also created a context so that I can change that state from child components such as RegistrationForm

When I try to call UserContext i get that it is undefined. Do I need to export it to use it ? If yes, then what is the purpose of context provider and consumer.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This is my code for app.js

function App() {
  //logged in user
  const [loggedUser, setLoggedUser] = useState(null);
  //create context for user
  const UserContext = createContext({
    loggedUser: null,
    setLoggedUser: () => {},
  });

  //value that will be passed to the context
  const value = {
    loggedUser,
    setLoggedUser,
  };

  //get the logged User if already exists
  useEffect(() => {
    setLoggedUser(localStorage.getItem("user"));
  }, []);

  .
  .
  .
  return (
      <UserContext.Provider value={value}>
        .
        .
        .
      </UserContext.Provider>
  );
}

This is where I am calling the useContext and I get the error that UserContext is not defined

export default function RegistrationForm({ onClick }) {
  const navigate = useNavigate();
  const { setLoggedUser } = useContext(UserContext);
.
.
.

>Solution :

Please define the UserContext outside app.js and export it.
Then import the UserContext in the file where you want to use it.

export const UserContext = createContext({
  loggedUser: null,
  setLoggedUser: () => {},
});

function App() {
  const [loggedUser, setLoggedUser] = useState(null);
  ... ... ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading