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 toIDLE
. ThefetchPostsStatus
value will change betweenIDLE
,PENDING
,SUCCESS
, andERROR
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 thefetchPostsStatus
state accordingly. At the start of the request, it should be set toPENDING
, on successful completion toSUCCESS
, and on error toERROR
. -
Disable the
Fetch posts
button when thefetchPostsStatus
is equal toPENDING
. -
Show an error message when the
fetchPostsStatus
is equal toERROR
. -
Show the list of posts only if the
fetchPostsStatus
is equal toSUCCESS
.
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 1400+ tech skills courses.