So I'm trying to fetch all 'places' given some location in React Native via the Google Places API. The problem is that after making the first call to the API, Google only returns 20 entries, and then returns a next_page_token, to be appended to the same API call url. So, I make another request to get the next 20 locations right after, but there is a small delay (1-3 seconds) until the token actually becomes valid, so my request errors.

I tried doing:

this.setTimeout(() => {this.setState({timePassed: true})}, 3000); 

But it's completely ignored by the app...any suggestions?

Update

I do this in my componentWillMount function (after defining the variables of course), and call the setTimeout right after this line.

axios.get(baseUrl) .then((response) => { this.setState({places: response.data.results, nextPageToken: response.data.next_page_token }); }); 
9

2 Answers

What I understood is that you are trying to make a fetch based on the result of another fetch. So, your solution is to use a TimeOut to guess when the request will finish and then do another request, right ?

If yes, maybe this isn't the best solution to your problem. But the following code is how I do to use timeouts:

// Without "this" setTimeout(someMethod, 2000 ) 

The approach I would take is to wait until the fetch finishes, then I would use the callback to the same fetch again with different parameters, in your case, the nextPageToken. I do this using the ES7 async & await syntax.

// Remember to add some stop condition on this recursive method. async fetchData(nextPageToken){ try { var result = await fetch(URL) // Do whatever you want with this result, including getting the next token or updating the UI (via setting the State) fetchData(result.nextPageToken) } catch(e){ // Show an error message } } 

If I misunderstood something or you have any questions, feel free to ask!

I hope it helps.

0

try this it worked for me:

 async componentDidMount() { const data = await this.performTimeConsumingTask(); if (data !== null) { // alert('Moved to next Screen here'); this.props.navigator.push({ screen:"Project1.AuthScreen"}) } } performTimeConsumingTask = async() => { return new Promise((resolve) => setTimeout( () => { resolve('result') }, 3000 ) ); } 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy