crodev
crodev

Reputation: 1491

How to call function after fetch() has finished

I am using react-native and I have fetch GET request which takes an array. Now I need this fetch() to finish getting that array so I can call a function which will handle this array and do something with it. How do I wait for it to finish?

This is my request:

componentWillMount() {
  console.log("will mount");
  fetch('SOME_API', {
    method: "GET",
    headers: {
      Accept: 'text/javascript',
      'Content-Type': 'text/javascript',
    }
  }).then(response = >response.json()).then(responseJson = >{
    this.setState(function(prevState, props) {
      return {
        questions: responseJson,
        loading: false
      }
    })
  })
}

And when this get request puts responseJson in state I want to call my function that will do something with that array.

If you need any more info please comment.

Upvotes: 15

Views: 35868

Answers (4)

Colin
Colin

Reputation: 1836

Use finally()

fetch('/URL')
  .then(response => response.json())
  .then(jsonResponse => {
    // Do your things
  }
  .catch(error => {
    console.error('Error:', error);
  })
  .finally(() => {
    // Call your function here
  });

Upvotes: 0

Mohammad
Mohammad

Reputation: 11

I added another .then at the end and put the function inside it. In my case, I wanted to log the data received by fetch:

fetch(url).then(some function).then(function(){
    console.log(fetchResultData)
})

Upvotes: 0

Saravanan
Saravanan

Reputation: 829

Just Define the function inside the class and call the function using this.{function_name} as below.

myFunction(responseJson) {
  // ... Your code ...
}
componentWillMount() {
  console.log("will mount");
  fetch(baseUrl + 'api/Customer/GetCustomerAccount/' + value, {
    method: 'GET',
  })
  .then((response) => response.json())
  .then((responseJson) => {
    this.myFunction(responseJson);
  })
}

Upvotes: 17

mr L
mr L

Reputation: 1018

Put an if statement in your render function:

 render(){

    if(this.state.loading){
        return(
            <View style={{flex: 1, padding: 20}}>
                // Your code if fetch() still fetching
            </View>
        )
     }

    return(
        <View style={{flex: 1, paddingTop:20}}>
            // Your code if fetch() has ended
            // the complete fetched data is this.state.questions
        </View>
    );
} 

Upvotes: 0

Related Questions