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.