Wait for react-promise to resolve before render

前端 未结 3 2226
离开以前
离开以前 2021-02-12 18:03

So I have a large set of data that I\'m retrieving from an API. I believe the problem is that my component is calling the renderMarkers function before the data is received from

相关标签:
3条回答
  • 2021-02-12 18:31

    So I have the similar problem, with react and found out solution on my own. by using Async/Await calling react Code snippet is below please try this.

     import Loader from 'react-loader-spinner'
    
     constructor(props){
        super(props);
        this.state = {loading : true}
      }
      getdata = async (data) => {
        return await data; 
      }
      getprops  = async (data) =>{
        if (await this.getdata(data)){
          this.setState({loading: false})
        }
      }
      render() {
      var { userInfo , userData} = this.props;
        if(this.state.loading == true){
          this.getprops(this.props.userData);
        } 
        else{
    //perform action after getting value in props
        }
        return (
          <div>
          {
               this.state.loading ? 
                 <Loader
                   type="Puff"
                   color="#00BFFF"
                   height={100}
                   width={100}
                 />
               :    
                  <MyCustomComponent/> // place your react component here
          }
          </div>
          )
    }
    
    0 讨论(0)
  • 2021-02-12 18:43

    Calling the render function before the API call is finished is fine. The wells is an empty array (initial state), you simply render nothing. And after receiving the data from API, your component will automatically re-render because the update of props (redux store). So I don't see the problem.

    If you really want to prevent it from rendering before receiving API data, just check that in your render function, for example:

    if (this.props.wells.length === 0) {
      return null
    }
    
    return (
      <div id="map" ref="map">
        {this.renderMarkers()}
      </div>
    )
    
    0 讨论(0)
  • 2021-02-12 18:50

    You could do something like this to show a Loader until all the info is fetched:

    class Map extends Component {
      constructor () {
        super()
        this.state = { wells: [] }
      }
    
      componentDidMount() {
        this.props.fetchWells()
          .then(res => this.setState({ wells: res.wells }) )
      }
    
      render () {
        const { wells } = this.state
        return wells.length ? this.renderWells() : (
          <span>Loading wells...</span>
        )
      }
    }
    
    0 讨论(0)
提交回复
热议问题