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

How to create get request using React Query in NextJS

1个答案

1

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.

bash
npm 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.

jsx
import { 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.

jsx
import { 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 useQuery hook 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 fetch to initiate a GET request and return the JSON response.
  • The useQuery hook returns an object containing states like data, error, and isLoading, 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 回复

你的答案