I want to make my code more readable, using async/await instead of using fetch().
My code needs to do the following :
- Fetch posts from API
- Select the random post (using find() array method)
- Make another API call based on the selected random post data.
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!
posts.find()is not asynchronous, you shouldn't useawait.posts.find()call will never match any of the posts, so you getundefined.