How to use AsyncStorage.setItem in fetch callback? - javascript

I got syntax error in my code.
async getJSON() {
await fetch(url)
.then((response) => response.text())
.then((responseText) => {
await AsyncStorage.setItem(STORAGE_KEY, responseText);
})
.catch((error) => {
console.warn(error);
});
},
Error is Unexpected token on await AsyncStorage.setItem(STORAGE_KEY, responseText);
I guess it's complaining await

For every await you need an async.
async getJSON() {
await fetch(url)
.then((response) => response.text())
.then(async (responseText) => { // <-- add async here
await AsyncStorage.setItem(STORAGE_KEY, responseText);
})
.catch((error) => {
console.warn(error);
});
},
Also... the point of async/await is to make the code look sync when is actually async. You can rewrite the above code like this:
async getJSON() {
try {
var response = await fetch(url);
var responseText = response.text();
await AsyncStorage.setItem(STORAGE_KEY, responseText);
} catch(error) {
console.warn(error);
}
}

Related

How to resolve multiple then() promise into one

In this code I used multiple then() methods, I just want to convert it into only one then, How it is possible.
getGreeting = () => {
fetch(url)
.then((response) => response.json())
.then((result) => result.data)
.then((data) => printCards(data))
.catch((err) => {
console.log(err);
});
};
notice the async and await keywords
fetch(url)
.then(async (response) => {
const json = await response.json();
printCards(json.data);
})
.catch((err) => {
console.log(err);
});
};

How to call multiple fetch APIs

I have to make a fetch call at a url and after getting its response I want to use those results to call another fetch. I have following code:-
async function getDate(request) {
let data;
console.log('handle request called')
await fetch('<first-url>')
.then(res => {
let urls = res.json()
console.log('urls are ', urls)
return urls.data
})
.then((urls) => {
let url = urls[0]
console.log('url is ', url)
return fetch(url)
})
.then((res) => {
data = res.body
})
.catch(() => {
console.log("something went wrong")
})
return new Response(data, {
headers: { 'content-type': 'text/html' },
})
}
I followed the above method after following this tutorial. However it does not seem to work and I am getting urls are {Promise:[Pending]}.
Here issue with return res.json(). res.json() is promisable object, so u have to resolve it to get data.
For your example:
const fetch = require("node-fetch");
async function getDate() {
let data;
console.log("handle request called");
return await fetch('<first-url>')
.then((res) => res.json())
.then((urls) => {
console.log("urls are ", urls);
if (urls.length)
return Promise.all(urls.map((url) => fetch(url).then((x) => x.json())));
return [];
})
.then((responses) => {
console.log("urls are ", responses);
return responses;
});
}
getDate().then(console.log);
Sample:
async function getDate() {
let data;
console.log("handle request called");
return await fetch("https://api.covid19api.com/countries")
.then((res) => res.json())
.then((urls) => {
console.log("urls are ", urls);
return urls;
});
}
getDate().then(console.log);

javascript fetch function getting syntax error

i want to fetch json data from openweathermap.org.but whenever i open my console it gives error(syntax error:JSON.parse() like this).and i am unable to find what's wrong with my code.plzz help thanks in advance.
<script>
console.log('about to fetch a rainbow');
async function catchRainbow() {
const response = await fetch('api.openweathermap.org/data/2.5/forecast/hourly?q=London,us&mode=xml&appid=e4386e3969c8d595d7f2f189cf2f786a');
const json= await response.json();
return json;
}
catchRainbow()
.then(json => {
console.log(json);
})
.catch(error => {
console.log('error!');
console.error(error);
});
</script>
You need to add the link prefix http:///https:// otherwise JS thinks you mean a local file.
console.log('about to fetch a rainbow');
async function catchRainbow() {
const response = await fetch('https://api.openweathermap.org/data/2.5/forecast/hourly?q=London,us&mode=xml&appid=e4386e3969c8d595d7f2f189cf2f786a');
const json = await response.json();
return json;
}
catchRainbow()
.then(json => {
console.log(json);
})
.catch(error => {
console.log('error!');
console.error(error);
});

AsyncStorage in a non async function

The following code:
_loginAsync = async () => {
fetch('localhost:3000/login')
.then((response) => response.json())
.then((responseJson) => {
await AsyncStorage.setItem('my-item', responseJson.item);
this.props.navigation.navigate('Home');
})
.catch((error) => {
console.error(error);
});
}
throws the error: Can not use keyword 'await' outside an async function.
Which is the proper way to valorize the my-item?
Your .then callback isn't marked as async, only the outer _loginAsync function is.
_loginAsync = async () => {
fetch('localhost:3000/login')
.then((response) => response.json())
.then(async (responseJson) => {
await AsyncStorage.setItem('my-item', responseJson.item);
this.props.navigation.navigate('Home');
})
.catch((error) => {
console.error(error);
});
}
That said, it seems weird to mix all of the .then and await forms here.
Using Async/Await Only
I think this is the most readable version. We just use async/await to await the fetch directly instead of working with its promise.
_loginAsync = async () => {
try {
const response = await fetch('localhost:3000/login');
await AsyncStorage.setItem('my-item', response.json().item);
this.props.navigation.navigate("Home")
} catch(error) {
console.error(error);
}
}
Using Promises Directly
You can (pretty much) always use an async function as a normal function that returns a promise as well. So instead of awaiting AsyncStorage.setItem we can just use its promise as part of our chain by returning it from then.
_loginAsync = () => {
fetch('localhost:3000/login')
.then((response) => response.json())
.then((responseJson) => AsyncStorage.setItem('my-item', responseJson.item))
.then(() => this.props.navigation.navigate('Home'))
.catch((error) => {
console.error(error);
});
}
If you have to make it work for your code, make the anonymous function for the block where await occurs to async.
_loginAsync = async () => {
fetch('localhost:3000/login')
.then((response) => response.json())
.then(async (responseJson) => {
await AsyncStorage.setItem('my-item', responseJson.item);
this.props.navigation.navigate('Home');
})
.catch((error) => {
console.error(error);
});
}
But I prefer this is a much better approach and looks more readable. Try this code instead.
_loginAsync = async () => {
try {
const response = await fetch('localhost:3000/login');
const responseJson = response.json()
await AsyncStorage.setItem('my-item', responseJson.item);
this.props.navigation.navigate('Home');
} catch (error) {
console.error(error);
}
}

react-native fetch async/await response filtering

I have response from my server like buildings : [record1, record2, ...] and I want to get only the array from that response. How can I get just the array from the Promise? I have tried some async/await things but I didn't understand how to use it in this code:
setupImpagination() {
....
fetch(pageOffset, pageSize, stats) {
return fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`)
.then(response => {
console.log('response.json() => ',response.json());
response.json()
})
.catch((error) => {
console.error(error);
});
}
});
}
.then way
fetch(pageOffset, pageSize, stats) {
return fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`)
.then(response => {
console.log('response.json() => ',response.json());
response.json()
}).then(responseJson => {
return responseJson.buildings
}).catch((error) => {
console.error(error);
});
}
});
async/await way:
async fetch(pageOffset, pageSize, stats) {
try {
const response = await fetch(`http://localhost:3000/api/building/all?skip=${pageOffset}&limit=${pageSize}`);
const responseJson = await response.json();
return responseJson.buildings;
} catch(error){
console.error(error);
}
async function fetchData (url, { type = 'json' } = {}) {
return await (await fetch(url))[type]();
}
// Example:
(async () => {
console.log(await fetchData('http://canskit.com', { type: 'text' }));
})();
As the original js on ES7, not aim at react-native

Categories