React useContext returns undefined
Asked Answered
S

1

14

I'm trying to use React Context to manage states for my project, but I can't seem to make it work for my CRA codebase this time while I had successful attempts on other projects. useContext returns undefined so I couldn't access the values inside the context, but I have double checked that my Provider is at my app root level. Appreciate any help.

This is my simplified App component:

import React, { useContext } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import './App.css';

import { PlayerContextProvider, PlayerContext } from 'contexts/PlayerContext';

const App = () => (
  <PlayerContextProvider>
    <Test />
    <Router>
      <Switch>
        <Route path="/" exact component={Home} />
      </Switch>
    </Router>
  </PlayerContextProvider>
);

const Test = () => {
  const values = useContext(PlayerContext);
  console.log('test values', values); // returns undefined!

  return <div>Hello World</div>;
};

export default App;

This is my context:

import React, { useState, createContext } from 'react';

const PlayerContext = createContext();

const PlayerContextProvider = ({ children }) => {
  const [players, setPlayers] = useState(['test']);

  const addPlayer = ({ name }) => {
    setPlayers([...players, { name }]);
  };

  const values = { players, addPlayer };
  console.log('context values', players); // shows ['test'] here

  return (
    <PlayerContext.Provider values={values}>
      <>
        {players}
        {children}
      </>
    </PlayerContext.Provider>
  );
};

export { PlayerContextProvider, PlayerContext };
Sideswipe answered 5/8, 2019 at 15:22 Comment(0)
C
26

You have a small typo.

Instead of values the correct is value without s.

<PlayerContext.Provider value={values}>

Edit:

If you are getting undefined and isn't because of the typo, you probably forgot to "wrap" a component with the Provider and the undefined value comes from the first argument of React.createContext() (which is undefined is you don't pass anything)

Cyanine answered 5/8, 2019 at 15:32 Comment(2)
Wow.. I was looking at the code for 5 minutes and just couldn't see it. Now I can't unsee it 😀Homology
This had me scratching my (wondering what I was doing wrong) for about 30minutes!Trembles

© 2022 - 2024 — McMap. All rights reserved.