How to use Tanstack Query v5 with Next.js 14 and React Server Components to fetch initial data with fetch from Next.js, pass that data to Tanstack and then make requests with Tanstack? Please use 'use server' directive during the first fetch in RSC
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To use Tanstack Query v5 with Next.js 14 and React Server Components (RSC) to fetch initial data, follow the steps below:
Install the necessary dependencies:
bash
npm install react-query next react
Create the Next.js app:
bash
npx create-next-app@latest
Setup your React Server Component. In your project, create a directory named src and inside that, create another directory named components. Inside this directory, create a new file named MyServerComponent.server.js and add the following code:
javascript
import {useServer} from 'react-dom/server'
import {useQuery, QueryClient, QueryClientProvider} from 'react-query'
import fetch from 'node-fetch'
async function fetcher(url) {
const res = await fetch(url)
const json = await res.json()
return json
}
function MyServerComponent() {
const {data, status} = useQuery('fetchData', () => fetcher('https://api.example.com/data'))
return useServer(
<div>
{status === 'loading' ? (
<div>Loading...</div>
) : status === 'error' ? (
<div>Error: {error.message}</div>
) : (
<div>{data}</div>
)}
</div>
)
}
const queryClient = new QueryClient()
export default function WrappedComponent() {
return (
<QueryClientProvider client={queryClient}>
<MyServerComponent />
</QueryClientProvider>
)
}
In the above code, we are using Tanstack's useQuery hook to fetch data from an API. We pass this data to our component using the useServer directive. Note that we are also handling loading and error states.
Create your Next.js page. In the pages directory, create a new file named index.js (or update the existing one) and add the following code:
javascript
import MyServerComponent from '../components/MyServerComponent.server'
export default function Home() {
return <MyServerComponent />
}
In this file, we are importing and using our server component.
Remember that, as of now, React Server Components (RSC) are still experimental, and the useServer directive is not yet available in stable React versions. You'd need to be using the experimental version of React and ReactDOM to use React Server Components and useServer directive. Also, note that Next.js 14 does not support React Server Components out of the box, and using them requires a custom setup.