I learned this manual https://reactjs.org/docs/context.html
And wrote this code
UserContext.js:
import React from 'react';
const UserContext = React.createContext();
export default UserContext;
App.js:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
id: '',
name: ''
};
}
componentDidMount() {
this.getAccountData();
}
async getAccountData() {
this.setState({
id: 123,
name: "Jacob"
});
}
render() {
return (
<UserContext.Provider value={this.state}>
<Account />
</UserContext.Provider>
);
}
}
Account.js:
class Account extends React.Component {
static contextType = UserContext;
render() {
return (
<UserContext.Consumer>
{user => (
<div className="account">
<p>{user.id} - {user.name}</p>
</div>
)}
</UserContext.Consumer>
)
}
}
The user.id variable remains an empty string! I tried to manually change this.context, but this also does not work, it makes a copy as it goes. In addition, there is nothing about this in the documentation.
Any help?
Top comments (2)
Are you getting any errors?
getAccountData
needs to bindthis
in constructor or should be declared with an arrow syntax.No mistakes
If i write
then it will work.
this attaches correctly. But setState or timers do not change the object that is inside UserContext.Consumer