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);
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.
React does not wait to render. There is no way to make it wait.
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 .
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.
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> ) } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With