When using NextJS with React Query to make GET requests, the basic steps are as follows:
1. Install Required Dependencies
First, ensure that React Query is installed in your project. If not, you can install it using npm or yarn.
bashnpm install react-query # Or yarn add react-query
2. Set Up React Query
In your NextJS project, you typically set up the React Query Provider in the _app.js or _app.tsx file. This ensures that you can use React Query's features in any component within your application.
jsximport { QueryClient, QueryClientProvider } from 'react-query'; function MyApp({ Component, pageProps }) { const queryClient = new QueryClient(); return ( <QueryClientProvider client={queryClient}> <Component {...pageProps} /> </QueryClientProvider> ); } export default MyApp;
3. Create and Use a Query
Assume you have an API with the URL https://api.example.com/data, and you want to fetch data from it. You can use the useQuery hook within a React component to initiate a GET request.
jsximport { useQuery } from 'react-query'; function FetchDataComponent() { const { data, error, isLoading } = useQuery('data', () => fetch('https://api.example.com/data').then(res => res.json() ) ); if (isLoading) return <div>Loading...</div>; if (error) return <div>An error occurred: {error.message}</div>; return ( <div> <h1>Data</h1> <pre>{JSON.stringify(data, null, 2)}</pre> </div> ); } export default FetchDataComponent;
Example Explanation:
- The first parameter of the
useQueryhook is the unique query key (here,'data'), which React Query uses to cache and remember the query state. - The second parameter is an async function; here, we use
fetchto initiate a GET request and return the JSON response. - The
useQueryhook returns an object containing states likedata,error, andisLoading, which you can use to control your UI display logic.
By following these steps, you can efficiently manage server state and caching in your NextJS project using React Query, enhancing application performance and user experience.
2024年6月29日 12:07 回复