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:
javascriptasync 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:
javascriptimport { 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:
- Check response: First, verify the
response.okproperty, which is a boolean indicating whether the response status code falls within the 200-299 range. - Status code evaluation: If
response.okisfalse, inspectresponse.statusto throw appropriate errors. - Error handling: In the component, use
isErroranderrorto 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 回复