0

Consider code below:

        componentDidMount(){
            const loginEmail = localStorage.getItem('loginEmail');
            const id = localStorage.getItem('id');

            Promise.all([
                fetch(`http://localhost:9000/api/users/view/${loginEmail}`)   // first API
                .then(value => 
                    value.json().then((res)=>{
                        this.setState({data: res.data});
                    })),
                fetch(`http://localhost:9000/api/event/view/${id}`)   // Second API
                .then(value => 
                    value.json().then((res)=>{
                        this.setState({data: res.data});
                    })),
                ])
                console.log(this.state.data)    // cant get the result
                .catch((err) => {
                    console.log(err);
                });
            }

This is what I am getting the response from console

enter image description here

So is it the way I do is wrong? By the way, My data from JSON api is in Object value.

Community
  • 1
  • 1
koko ka
  • 107
  • 4
  • 17
  • 2
    `setState` is asynchronous—that's why `this.state.data` is not what you're expecting. Check this question out: [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – coreyward Feb 28 '20 at 14:24

1 Answers1

0
componentDidMount() {
 Promise.all([
   fetch(`http://localhost:9000/api/users/view/${loginEmail}`).then(blob => blob.json()),
   fetch(`http://localhost:9000/api/event/view/${id}`).then(blob => blob.json())
 ])
 .then([response1, response2] => {
   this.setState(prevState => {
    // do your operations
    return {
     ...prevState
    }
   })
 })
 .catch(error => {
  // handle error
 })
}
AngelSalazar
  • 3,080
  • 1
  • 16
  • 22