Hysii
Hysii

Reputation: 772

Using a function callback inside another function

I have my react element with a couple of functions inside. I want to use the callback of one function inside another function as a variable. Both functions are using Fetch API.

fetchA = () => {
    var data = new FormData();
    data.append('file', this.state.selectedFile, this.state.selcetedFile.name);
    fetch('/files', {method: 'POST', body: data})
      .then(response => {
        return response.json()})
      .then(function(json) {
        console.log(json));})
      .catch(function(error) {
         console.log(error)
      });
}

and

fetchB = () => {
    fetch('/trust', {method: 'put', body: **HERE**})
      .then(response => {
        console.log('SUCCESS')})
      .catch(function(error) {
         console.log(error)
      });
}

You can see in the body of the second fetch call is where i would like to reference the json that was generated in the response of my first function. Can anybody recommend a simple solution for this?

Upvotes: 1

Views: 76

Answers (2)

dance2die
dance2die

Reputation: 36915

You can use async/await to make it look like a synchronous operation.

fetchA = async () => {
    var data = new FormData();
    data.append('file', this.state.selectedFile, this.state.selcetedFile.name);
    const response = await fetch('/files', {method: 'POST', body: data});
    return await response.json();
}

fetchB = async () => {
    const body = await fetchA();
    fetch('/trust', {method: 'put', body})
      .then(response => {
        console.log('SUCCESS')})
      .catch(function(error) {
         console.log(error)
      });
}

Upvotes: 0

Tholle
Tholle

Reputation: 112807

If you want to run fetchB with the result from fetchA right after fetchA is done, you can just call fetchB with the result of fetchA:

Example

class App extends React.Component {
  fetchA = () => {
    const { selectedFile } = this.state;
    const data = new FormData();

    data.append("file", selectedFile, selectedFile.name);

    fetch("/files", { method: "POST", body: data })
      .then(response => {
        return response.json();
      })
      .then(result => {
        this.fetchB(result);
      })
      .catch(error => {
        console.log(error);
      });
  };

  fetchB = data => {
    fetch("/trust", { method: "put", body: data })
      .then(response => {
        console.log("SUCCESS");
      })
      .catch(error => {
        console.log(error);
      });
  };

  // ...
}

Upvotes: 2

Related Questions