Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for react-promise to resolve before render

Tags:

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 the promise.

So I am wondering how I can wait for the promise to resolve the data completely before calling my renderMarkers function?

class Map extends Component {  componentDidMount() {   console.log(this.props)   new google.maps.Map(this.refs.map, {     zoom: 12,     center: {       lat: this.props.route.lat,       lng: this.props.route.lng     }   }) }  componentWillMount() {   this.props.fetchWells() }  renderMarkers() {   return this.props.wells.map((wells) => {     console.log(wells)   }) }  render() {   return (     <div id="map" ref="map">       {this.renderMarkers()}     </div>   )  } }   function mapStateToProps(state) {   return { wells: state.wells.all }; }  export default connect(mapStateToProps, { fetchWells })(Map); 
like image 751
Edward Smith Avatar asked Feb 09 '17 09:02

Edward Smith


People also ask

How do you wait until a promise is resolved React?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

How wait for render React?

React does not wait to render. There is no way to make it wait.

What function is called before render?

getDerivedStateFromProps. The getDerivedStateFromProps() method is called right before rendering the element(s) in the DOM. This is the natural place to set the state object based on the initial props . It takes state as an argument, and returns an object with changes to the state .

How do you render promise objects in React?

To get promise value in React and JavaScript, we can use await . to create the getAnswer function that calls fetch with await to get the response data from the promise returned by fetch . Likewise, we do the same with the json method.


1 Answers

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>     )   } } 
like image 131
Lionel T Avatar answered Sep 17 '22 06:09

Lionel T