Tuesday, May 14, 2024
 Popular · Latest · Hot · Upcoming
144
rated 0 times [  149] [ 5]  / answers: 1 / hits: 8855  / 3 Years ago, sat, october 2, 2021, 12:00:00

Im trying to pass and update a state with useContext;


App.js


import Home from './components/Home'
const UserContext = createContext();

function App() {
const [name, setName] = useState('Name');

return (
<UserContext.Provider value={{name, setName}}>
<Home/>
</UserContext.Provider>
);
}

export default App;

Home.js


import UserContext from '../../App'

function Home() {
const user = useContext(UserContext);

return (
<>
<label>Your name:</label>
<input type='text' onChange={e => user.setName(e.target.value)} />
<p>{user.name}</p>
</>
)
}

export default Home;

Im getting this error



TypeError: Cannot read properties of undefined (reading 'name');



How is the correct way to pass state between components with useContext?


More From » reactjs

 Answers
8

You need to export your UserContext, so it can be imported in the components that need it:


export const UserContext = React.createContext();

function App() {
const [name, setName] = useState('Name');

return (
<UserContext.Provider value={{ name, setName }}>
<Home />
</UserContext.Provider>
);
}

Afterwards you can import it in your App component:


import { UserContext } '../../App'

function Home() {
const user = useContext(UserContext);

return (
<>
<label>Your name:</label>
<input type='text' onChange={e => user.setName(e.target.value)} />
<p>{user.name}</p>
</>
)
}

[#804] Saturday, September 25, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kylanalis

Total Points: 438
Total Questions: 85
Total Answers: 102

Location: Barbados
Member since Sun, Nov 27, 2022
1 Year ago
kylanalis questions
Tue, Oct 13, 20, 00:00, 4 Years ago
Thu, Feb 13, 20, 00:00, 4 Years ago
Tue, Jan 7, 20, 00:00, 4 Years ago
Thu, Jan 2, 20, 00:00, 4 Years ago
;