DEV Community 👩‍💻👨‍💻

Dieldore
Dieldore

Posted on

variable passed through context does not change in the child when changing in the parent and vice versa

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)

Collapse
dance2die profile image
Sung M. Kim

Are you getting any errors?

getAccountData needs to bind this in constructor or should be declared with an arrow syntax.

Collapse
dieldore profile image
Dieldore Author • Edited on

No mistakes
If i write

this.state = {
      id: '123',
};

then it will work.
this attaches correctly. But setState or timers do not change the object that is inside UserContext.Consumer

🌚 Friends don't let friends browse without dark mode.

Good news! You can update to dark mode in your DEV settings.