0

I want to make my code more readable, using async/await instead of using fetch().

My code needs to do the following :

  1. Fetch posts from API
  2. Select the random post (using find() array method)
  3. 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!

11
  • 1
    Is this not working? What is your question? Commented Jun 11, 2018 at 19:34
  • @zero298 just edited Commented Jun 11, 2018 at 19:43
  • 1
    posts.find() is not asynchronous, you shouldn't use await. Commented Jun 11, 2018 at 19:48
  • 1
    The problem is that sometimes the callback function in your posts.find() call will never match any of the posts, so you get undefined. Commented Jun 11, 2018 at 19:51
  • It has nothing to do with changing the coding style, you should have the same problem with the original code. Commented Jun 11, 2018 at 19:51

1 Answer 1

2

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)];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.