Cannot fetch data before render

reactjs axios fetch

6 观看

1回复

1 作者的声誉

I am try to get data with axios before i render it. I am using axios and getting data in ComponentDidMount. I also tried to get in Component WillMount but still not working how can i solve this problem????

I also tried to get in Component WillMount but still not working, i need the data before render coz i have to pass to another component. After that i put on a button and after few second from loaded website it works as expected

componentDidMount() {
    axios
      .get(
        "https://us-central1-punjabi-music-downloader.cloudfunctions.net/getTracks"
      )
      .then(res => this.setState({ tracks: res.data }));
  }
  render() {
    return (
      <div>
        <h1>Music tracks</h1>
        {this.state.tracks[0].name}
      </div>
    );
  }

I RECEIVE .name is not defined.

作者: Gopal Singh 的来源 发布者: 2019 年 8 月 9 日

回应 1


0

5155 作者的声誉

You just need to check if data is available then only you need to set it like

{this.state.tracks && this.state.tracks.length > 0 ? <span>this.state.tracks[0].name</span> : null}
作者: Dhaval Patel 发布者: 2019 年 8 月 9 日
32x32