react how to await fetch code example
Example 1: fetch await
async function getUserAsync(name)
{
let response = await fetch(`https://api.github.com/users/${name}`);
let data = await response.json()
return data;
}
getUserAsync('yourUsernameHere')
.then(data => console.log(data));
Example 2: await fetch in react
async function fetchFunction() {
try{
const response = await fetch(`http://url.com`);
const json = await response.json();
}
catch(err) {
throw err;
console.log(err);
}
}
Example 3: async await class component react
async componentDidMount() {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
const json = await response.json();
console.log(json);
}