0

I have tried numerous ways to set state but for some reason, the state never gets updated.this is the JSON data that I want my state to change to

export class Provider extends Component {
  state = {
    posts: [],
    profileinfo: {},
    dispatch: action => this.setState(state => reducer(state, action))
  };

  componentDidMount() {
    fetch("http://localhost:3001/login").then(response =>
      response
        .json()
        .then(data => this.setState({ profileinfo: data.firstname }))
    );
    console.log(this.state.profileinfo);
  }

  render() {
    // ...
  }
}
Moshe Slavin
  • 5,127
  • 5
  • 23
  • 38
CryBaby
  • 47
  • 8

1 Answers1

0

setState is asynchronous. Your console log probably triggers before the state got updated. If you want to see the result after the setState call, do it this way:

data => this.setState({ profileinfo: data.firstname }, () => {
  console.log(this.state);
});
Nikola
  • 981
  • 1
  • 10
  • 20
  • the profile info still doesn't get updated as the profile info is stored in context api ,I am trying to fetch the value of it – CryBaby Mar 19 '19 at 10:55
  • So actually, your fetch doesn't work and you are not getting the data? – Nikola Mar 19 '19 at 10:58
  • If your profile info is stored inside the context, you don't fetch it's value. You use context ```Provider``` and ```Consumer``` to access the values. Read about it here:https://reactjs.org/docs/context.html and here: https://stackoverflow.com/a/49870973/6036881 – Nikola Mar 19 '19 at 11:10
  • Yes for that i need to set the state so that i can access the value from another component .As of now it returns undefined when I try to print the value – CryBaby Mar 19 '19 at 11:15