0

I am using promise.all inside componentdidmount to get response.data from two apis.

constructor(){
    super();
       this.state = {
        data: [],
        p1: [],
        p2: []
       };
  }

  async componentDidMount() {
    const [res1, res2] = await Promise.all([
      axios.get(api1),
      axios.get(api2)
    ]);
    this.setState({
      p1: res1.data,
      p2: res2.data
    });
    console.log("this.state.p1" ,this.state.p1)
    console.log("this.state.p2" ,this.state.p2)
  }

Sometimes both this.state.p1 and this.state.p2 return correct data but sometimes when I refresh my page this.state.p1 returns data of this.state.p2 and this.state.p2 becomes empty.

  • Don't put async on componentDidMount. Create an anonymous function inside it with async and then call it. componentDidMount() { const myAnony = async () => await Promise.all(...); myAnony(); – Steve Tomlin Jul 30 '21 at 06:39
  • 1
    You cannot use `console.log` immediately after `setstate`. Since it is `asyc`. Use the console.log in your render, since after the state change, render would be called and you should see the new data in render. – Panther Jul 30 '21 at 06:40
  • @Panther Getting the same issue even after using console.log inside render – Shubhi Manral Jul 30 '21 at 07:02
  • @SteveTomlin How do I setState as response.data returned from the apis ? Can you please add a code snippet here, which I can refer to? Thanks in advance! – Shubhi Manral Jul 30 '21 at 07:04
  • @ShubhiManral you can bind it like this. myAnony.bind(this) – Steve Tomlin Jul 30 '21 at 09:59
  • @SteveTomlin the issue still exits – Shubhi Manral Jul 30 '21 at 16:49

0 Answers0