Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 723
crodev Avatar asked Aug 30 '18 13:08

crodev


People also ask

How do you call a function in Fetch?

Use the fetch() method to return a promise that resolves into a Response object. To get the actual data, you call one of the methods of the Response object e.g., text() or json() . These methods resolve into the actual data.

What does the fetch () method return?

fetch() The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available. The promise resolves to the Response object representing the response to your request.

Is fetch a callback?

We start by defining the elf function getGiftForChild() which takes a child's name as input and fetches the gift from our URL using fetch() . This function will return a response in the form of a Promise . In fact, this is also a way of using callbacks.

How do you store fetch responses in variables?

Approach: First make the necessary JavaScript file, HTML file and CSS file. Then store the API URL in a variable (here api_url). Define a async function (here getapi()) and pass api_url in that function. Define a constant response and store the fetched data by await fetch() method.


1 Answers

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);
  })
}
like image 93
Saravanan Avatar answered Oct 16 '22 17:10

Saravanan