How to call function after fetch() has finished

20,488

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);
  })
}
Share:
20,488
crodev
Author by

crodev

Ruby on Rails developer from Croatia.

Updated on July 23, 2022

Comments

  • crodev
    crodev almost 2 years

    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.

    Thanks!

  • n4ks
    n4ks over 4 years
    But what if I use redux and make a request to the server through action creators. The request to the server does not occur in the component, where it will be most correct to check if the data has loaded if I need to do something with them? For example, apply some kind of filter. Use componentDidUpate() for that?
  • Saravanan
    Saravanan over 4 years
    Make an async request and return promise from the action either resolve or reject and catch the response or error whatever in the calling function inside the component. So you get the correct way to bind the request with the component