Reputation: 279
I want to make my code more readable, using async/await instead of using fetch().
My code needs to do the following :
The way I did it using fetch()
componentDidMount() {
const postsURL = 'https://jsonplaceholder.typicode.com/posts';
fetch(postsURL)
.then(res => res.json())
.then(posts => {
const randomNumber = Math.floor(Math.random() * 100);
const randomPost = posts.find(post => post.id === randomNumber);
fetch(
`https://jsonplaceholder.typicode.com/users/${
randomPost.userId
}`
).then(res => {
res.json().then(user => {
this.setState(() => {
return {
posts: posts,
showingPost: randomPost,
showingUser: user
};
});
});
});
})
.catch(err => console.log(err));
}
Now I'm trying to convert this code altogether into one async function getData()
async getData() {
// get posts
const getPostsResponse = await fetch(
'https://jsonplaceholder.typicode.com/posts'
);
const posts = await getPostsResponse.json();
// get showingPost
const randomPost = posts.find(
post => post.id === Math.floor(Math.random() * 100)
);
//get user
const getUserResponse = await fetch(
`https://jsonplaceholder.typicode.com/users/${randomPost.userId}`
);
const user = await getUserResponse.json();
// return/setState
return this.setState(() => {
return {
posts: posts,
showingPost: randomPost,
showingUser: user
};
});
}
componentDidMount() {
this.getData();
}
The problem is - randomPost
variable in this async function sometimes returns undefined. It has to be set before moving to the next API call.
How do I properly use find(), or any other method inside async/await function between 2 API calls? Thanks!
Upvotes: 0
Views: 263
Reputation: 780724
You change the way you're calling find()
. In the code that uses async/await
, you're calculating a different random number to test each array element against, but in the original code you just calculate randomNumber
once. The chance of finding a match in the second way is very low.
So do the same thing in the new code.
async getData() {
// get posts
const getPostsResponse = await fetch(
'https://jsonplaceholder.typicode.com/posts'
);
const posts = await getPostsResponse.json();
// get showingPost
const randomNumber = Math.floor(Math.random() * 100);
const randomPost = await posts.find(
post => post.id === randomNumber
);
A simpler way to pick a random element of an array is:
const randomPost = posts[Math.floor(Math.random() * posts.length)];
Upvotes: 2