-1

I am trying to fetch data from an endpoint in react but don't know exactly how can I wait for the called function to return and then pass the cursor to next line.

FetchData.js

// ...
componentDidMount () {
        const url = 'http...';
        const options = {
            headers: {'Content-Type': 'application/json'},
            method: 'GET'
        }
        const data = fetchDataFromUrl(url, options);

        this.setState({ item: data },
            () => this.updateItem())
}
console.log(this.state.item)
// ...

fetchData.js

export const fetchDataFromUrl = (url, options) => {
    const repsonse = fetch(url, options)
    .then(res  => res.json())
    .then(data => { 
        return data 
    })
}

This does return the data but in console.log() I get undefined, after sometime (ie in some other function) I am able to see the data contents. How can I wait for the fetchDataFromUrl function to fetch the data before the state gets updated. I used const data = async() => fetchDataFromUrl(url, options); but it does not help.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Ashish Mysterio
  • 177
  • 1
  • 5
  • 13

1 Answers1

0

You can simply use, async and await for your requirement

componentDidMount () {
      this.getData()
}

getData= async()=>{
const url = 'http...';
        const options = {
            headers: {'Content-Type': 'application/json'},
            method: 'GET'
        }
        const data = await fetchDataFromUrl(url, options);

        this.setState({ item: data },
            () => this.updateItem())
}

user fetch function should also be async function.

export const fetchDataFromUrl = async(url, options) => {
    const repsonse = await fetch(url, options);
      return repsonse; //Modify you response
}
Mr.Throg
  • 925
  • 6
  • 21