kanuos
kanuos

Reputation: 1195

useContext returning undefined

I am using react-context to create and use contexts. I am unable to use the contexts in the children components of the context-provider.

I can access the contexts on the App context. But whenever I tried to access to separate components the useContext returns undefined.

My App component looks like this.

<div className="App">
    <Navbar />
    <Header/>
<InstructorContextProvider>
<InstructorPage />
</InstructorContextProvider>
</div>

The instructorContext looks like :

const InstructorContextProvider = (props) => {
const [instructorList] = useState([1,2,3,4]); 
return (
   <InstructorContext.Provider value = {[...instructorList]}>
       {props.children}
   </InstructorContext.Provider>

The InstructorPage component returns undefined when the InstructorContext is used.

const InstructorPage = () => {
const [...instructorList] = useContext(InstructorContext);
console.log(instructorList);
return <h1> hello world </h1>
}

Upvotes: 1

Views: 2623

Answers (1)

Vencovsky
Vencovsky

Reputation: 31565

You don't need to use [...instructorList], just use it like instructorList.

And also, if you look at this codesandbox everything is working fine.

Upvotes: 2

Related Questions