乐闻世界logo
搜索文章和话题

How to use pending and status in useFetch in Nuxt 3?

1个答案

1

In Nuxt 3, useFetch is a powerful composable API that helps developers fetch data on the server-side or client-side while conveniently managing loading states and response states. By appropriately utilizing the pending and status properties in your project, you can achieve a smoother user experience and make data state handling during development more transparent.

Using pending

pending is a boolean value indicating whether a request is currently in progress. This is particularly useful when you need to display a loading indicator or other loading state prompts.

Example:

Suppose we need to fetch user data from an API, and the page should display a loading state while data is being loaded.

vue
<template> <div> <p v-if="isPending">Loading...</p> <p v-else>{{ userData.name }}</p> </div> </template> <script setup> import { useFetch } from '#app' const { data: userData, pending: isPending } = useFetch('/api/user') </script>

In this example, when isPending is true (indicating data is being fetched), the page displays "Loading...". Once data loading completes, isPending becomes false, and the page shows the user's name.

Using status

status is a response status code used to determine the outcome of a request (e.g., 200, 404, 500). This is valuable for error handling and displaying different information based on the response status.

Example:

Continuing with the user data example, we can display different content based on the response status.

vue
<template> <div> <p v-if="isPending">Loading...</p> <p v-else-if="status === 200">{{ userData.name }}</p> <p v-else-if="status === 404">User information not found.</p> <p v-else>Failed to load. Please try again later.</p> </div> </template> <script setup> import { useFetch } from '#app' const { data: userData, pending: isPending, status } = useFetch('/api/user') </script>

In this example, the displayed content is determined by the value of status. If the status code is 200, it shows the user's name; if it is 404, it displays "User information not found"; for other status codes, it shows a generic error message.

Summary

Using pending and status with useFetch in Nuxt 3 effectively manages various states during data loading, enhancing user experience and making state handling during development more explicit. By leveraging these properties appropriately, you can create richer and more user-friendly interaction effects in your application.

2024年7月24日 17:32 回复

你的答案