Skip to content

Commit 698f3b1

Browse files
committed
docs: update SSR guide for nuxt2
1 parent 2be2a79 commit 698f3b1

File tree

1 file changed

+23
-12
lines changed
  • docs/framework/vue/guides

1 file changed

+23
-12
lines changed

docs/framework/vue/guides/ssr.md

+23-12
Original file line numberDiff line numberDiff line change
@@ -82,11 +82,14 @@ export default (context) => {
8282
const queryClient = new QueryClient({
8383
defaultOptions: { queries: { staleTime: 5000 } },
8484
})
85-
const options = { queryClient }
8685

87-
Vue.use(VueQueryPlugin, options)
86+
if (process.server) {
87+
context.ssrContext.VueQuery = queryClient
88+
}
8889

8990
if (process.client) {
91+
Vue.use(VueQueryPlugin, { queryClient })
92+
9093
if (context.nuxtState && context.nuxtState.vueQueryState) {
9194
hydrate(queryClient, context.nuxtState.vueQueryState)
9295
}
@@ -100,7 +103,7 @@ Add this plugin to your `nuxt.config.js`
100103
module.exports = {
101104
...
102105
plugins: ['~/plugins/vue-query.js'],
103-
};
106+
}
104107
```
105108

106109
Now you are ready to prefetch some data in your pages with `onServerPrefetch`.
@@ -110,7 +113,7 @@ Now you are ready to prefetch some data in your pages with `onServerPrefetch`.
110113
- Prefetch all the queries that you need with `queryClient.prefetchQuery` or `suspense`
111114
- Dehydrate `queryClient` to the `nuxtContext`
112115

113-
```js
116+
```vue
114117
// pages/todos.vue
115118
<template>
116119
<div>
@@ -129,18 +132,26 @@ import { useQuery, useQueryClient, dehydrate } from "@tanstack/vue-query";
129132
130133
export default defineComponent({
131134
setup() {
135+
// Get QueryClient either from SSR context, or Vue context
136+
const { ssrContext } = useContext()
137+
// Make sure to provide `queryClient` as a second parameter to `useQuery` calls
138+
const queryClient = (ssrContext != null && ssrContext.VueQuery) || useQueryClient()
139+
132140
// This will be prefetched and sent from the server
133-
const { refetch, data, suspense } = useQuery("todos", getTodos);
141+
const { data, refetch, suspense } = useQuery({
142+
queryKey: ['todos'],
143+
queryFn: getTodos,
144+
}, queryClient)
134145
// This won't be prefetched, it will start fetching on client side
135-
const { data2 } = useQuery("todos2", getTodos);
136-
137-
const { ssrContext } = useContext();
138-
const queryClient = useQueryClient();
146+
const { data2 } = useQuery({
147+
queryKey: "todos2",
148+
queryFn: getTodos,
149+
}, queryClient)
139150
140151
onServerPrefetch(async () => {
141-
await suspense();
142-
ssrContext.nuxt.vueQueryState = dehydrate(queryClient);
143-
});
152+
await suspense()
153+
ssrContext.nuxt.vueQueryState = dehydrate(queryClient)
154+
})
144155
145156
return {
146157
refetch,

0 commit comments

Comments
 (0)