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

How to hande response status codes in React Query

1个答案

1

When using React Query to handle API requests, managing response status codes is a key component as it enables appropriate actions based on server responses. React Query itself does not directly handle HTTP status codes; instead, it focuses on data fetching and cache management. Handling status codes is typically implemented within the data fetching function.

Example:

Consider using a function fetchData to retrieve data from the server, which employs the fetch API to call a URL and process the response:

javascript
async function fetchData(url) { const response = await fetch(url); if (!response.ok) { // Handle different status codes switch(response.status) { case 400: throw new Error("Invalid request parameters"); case 401: throw new Error("Unauthorized access"); case 403: throw new Error("Forbidden access"); case 404: throw new Error("Resource not found"); case 500: throw new Error("Internal server error"); default: throw new Error("Unknown error"); } } return response.json(); }

Next, integrate the useQuery hook from React Query into a React component to utilize fetchData and manage potential errors:

javascript
import { useQuery } from 'react-query'; function MyComponent() { const { data, error, isError, isLoading } = useQuery('data', () => fetchData('https://api.example.com/data')); if (isLoading) return <div>Loading...</div>; if (isError) return <div>Error: {error.message}</div>; return ( <div> <h1>Data loaded</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); }

Handling Logic:

  1. Check response: First, verify the response.ok property, which is a boolean indicating whether the response status code falls within the 200-299 range.
  2. Status code evaluation: If response.ok is false, inspect response.status to throw appropriate errors.
  3. Error handling: In the component, use isError and error to detect and display error messages.

This approach ensures responsive handling of different status codes, such as redirecting users or presenting error messages.

2024年6月29日 12:07 回复

你的答案