Challenge: API States

Practice what we’ve learned about the API states.

Problem statement

Displaying appropriate feedback during API requests can improve user experience, as users are not left wondering if anything is happening on the website in response to their actions. Therefore, it’s a good practice to display some kind of feedback, such as a loader or message during an API request and then a success or an error message. Your task is to add appropriate feedback to an API request that’s used to fetch a list of posts.

Challenge

All the necessary code has been provided for you. The starter code for this challenge is the solution for the previous one, which consisted of adding fetch users functionality while utilizing the API Layer. When a user clicks on the “Fetch posts” button that’s rendered in the src/components/DisplayPosts.vue, its text should change to “Fetching posts” and the fetch posts requests should start. When the request to fetch posts succeeds, a list of post titles should be displayed. However, if it fails, then an error, “Could not fetch posts”, should be displayed. To store the current state of the API request, you should utilize one stateful value called fetchPostsStatus, that can be updated from within the initFetchPosts method. What’s more, the “Fetch posts” button should be disabled when the request is pending.

The fetchPosts request has about a 50% chance of throwing an error.

All the code changes should be done in the DisplayPosts.vue component.

This exercise should be solved with Vue 3’s Options API.

Get hands-on with 1400+ tech skills courses.