It is my next.js project
I have separately made the useContext folder and there I wrote my object or data which I want to use by my every files or components , and to do so I enclosed my _app.js file with the context one, but when I am using it in my one of the page, it showing undefined error. Unable to understand
Below am sending my every bit of fies
useContext/useContextherehere.js
import React, { createContext, useContext} from 'react';
const UserContext = createContext();
const UseContexthere = ({children}) => {
const biodata = {
name : "Manish",
profession : "Coder & Rapper",
age : 25
}
return (
<>
<UserContext.Provider value={{biodata}}>
{children}
</UserContext.Provider>
</>
)
}
export default UseContexthere;
_app.js — in next.js
import '@/styles/globals.css';
import UseContexthere from './useContext/useContexthere';
export default function App({ Component, pageProps }) {
return (
<UseContexthere>
<Component {...pageProps} />
</UseContexthere>
)
}
about.js — using here my context thing
import React, {useContext} from 'react';
import UseContexthere from './useContext/useContexthere';
const About = () => {
const user = useContext(UseContexthere);
return (
<div>
<div>
<h3>Following data is coming through useContext Hook</h3>
<p>Hey my name is {user.name}</p>
</div>
</div>
)
}
export default About
but than it showing me error of undefined. What am I doing wrong?
3
Answers
You are creating an object with a
biodata
property, but then you are trying to access a name property. To fix this, either change the provided value to be just the biodata object, not nested inside another object:Or change the way you consume the context to expect the
biodata
property:This is what is essentially happening because of double curly braces.
You are not passing
biodata
, but an object which hasbiodata
as a key.Just update your code like:
Edit:
Here’s a NextJS stackblitz of the details of this answer:
https://stackblitz.com/edit/stackblitz-starters-esbbm1?file=pages%2Findex.js
Answer:
It’s because you’re not using the correct import
You need to export the actual context (not just your provider component):
and in your consuming component you need to use that export, not the default export:
In practice, what is common in React applications is the hook is also exported from the place the context is created, just to keep things simpler:
This is in addition to the typos details by the other answers