Solution: API States

Here’s the solution of how to add API states to an API request call.

We'll cover the following

Solution

This challenge required you to show different content based on the current API state. Below are the required changes:

For the src/components/DisplayPosts.vue file:

  • Add a new state called fetchPostsStatus with the value set to IDLE. The fetchPostsStatus value will change between IDLE, PENDING, SUCCESS, and ERROR depending on the status of the API request to fetch posts.

  • Add a computed prop to return the text for the button based on the value of fetchPostsStatus. This could be accomplished without using the computed property. Adding this logic directly in the template would work as well.

  • Modify the initFetchPosts method to update the fetchPostsStatus state accordingly. At the start of the request, it should be set to PENDING, on successful completion to SUCCESS, and on error to ERROR.

  • Disable the Fetch posts button when the fetchPostsStatus is equal to PENDING.

  • Show an error message when the fetchPostsStatus is equal to ERROR.

  • Show the list of posts only if the fetchPostsStatus is equal to SUCCESS.

Let’s run the following code to understand how the solution above works.

Note: The code below may take a while to run. When the server starts, go to the app URL, and you will see the output.

Get hands-on with 1200+ tech skills courses.