Skip to content

Commit c525435

Browse files
author
Guillaume Chau
committed
docs: use ssrPrefetch in data guide
1 parent 0b184bd commit c525435

File tree

1 file changed

+78
-132
lines changed

1 file changed

+78
-132
lines changed

docs/guide/data.md

Lines changed: 78 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,9 @@
22

33
## Data Store
44

5-
During SSR, we are essentially rendering a "snapshot" of our app, so if the app relies on some asynchronous data, **these data need to be pre-fetched and resolved before we start the rendering process**.
5+
During SSR, we are essentially rendering a "snapshot" of our app. The asynchronous data from our components needs to be available before we mount the client side app - otherwise the client app would render using different state and the hydration would fail.
66

7-
Another concern is that on the client, the same data needs to be available before we mount the client side app - otherwise the client app would render using different state and the hydration would fail.
8-
9-
To address this, the fetched data needs to live outside the view components, in a dedicated data store, or a "state container". On the server, we can pre-fetch and fill data into the store before rendering. In addition, we will serialize and inline the state in the HTML. The client-side store can directly pick up the inlined state before we mount the app.
7+
To address this, the fetched data needs to live outside the view components, in a dedicated data store, or a "state container". On the server, we can pre-fetch and fill data into the store while rendering. In addition, we will serialize and inline the state in the HTML after the app has finished rendering. The client-side store can directly pick up the inlined state before we mount the app.
108

119
We will be using the official state management library [Vuex](https://github.com/vuejs/vuex/) for this purpose. Let's create a `store.js` file, with some mocked logic for fetching an item based on an id:
1210

@@ -80,34 +78,79 @@ So, where do we place the code that dispatches the data-fetching actions?
8078

8179
The data we need to fetch is determined by the route visited - which also determines what components are rendered. In fact, the data needed for a given route is also the data needed by the components rendered at that route. So it would be natural to place the data fetching logic inside route components.
8280

83-
We will expose a custom static function `asyncData` on our route components. Note because this function will be called before the components are instantiated, it doesn't have access to `this`. The store and route information needs to be passed in as arguments:
81+
We will use the `ssrPrefetch` option in our components. This option is recognized by the server renderer and will be pause the component render until the promise it returns is resolved. Since the component instance is already created at this point, it has access to `this`.
8482

8583
``` html
8684
<!-- Item.vue -->
8785
<template>
88-
<div>{{ item.title }}</div>
86+
<!-- Loading -->
87+
<div v-if="loading">Loading...</div>
88+
<!-- Fetch error -->
89+
<div v-else-if="error">An error occured</div>
90+
<!-- Item is undefined -->
91+
<div v-else-if="!item">Item not found</div>
92+
<!-- Normal render -->
93+
<div v-else>{{ item.title }}</div>
8994
</template>
9095

9196
<script>
9297
export default {
93-
asyncData ({ store, route }) {
94-
// return the Promise from the action
95-
return store.dispatch('fetchItem', route.params.id)
98+
data () {
99+
return {
100+
loading: false,
101+
error: false
102+
}
96103
},
97104
98105
computed: {
99106
// display the item from store state.
100107
item () {
101108
return this.$store.state.items[this.$route.params.id]
102109
}
110+
},
111+
112+
// This will be called by the server renderer automatically
113+
ssrPrefetch () {
114+
// return the Promise from the action
115+
// so that the component waits before rendering
116+
return this.fetchItem()
117+
},
118+
119+
mounted () {
120+
// This is run only on the client
121+
// If we didn't already do it on the server
122+
// we fetch the item (will first show the loading text)
123+
if (!this.item) {
124+
this.fetchItem()
125+
}
126+
},
127+
128+
methods: {
129+
fetchItem () {
130+
this.loading = true
131+
this.error = false
132+
// return the Promise from the action
133+
return store.dispatch('fetchItem', this.$route.params.id)
134+
.then(() => {
135+
// Everything is ok!
136+
this.loading = false
137+
})
138+
.catch(error => {
139+
// An error occured
140+
this.loading = false
141+
this.error = true
142+
// We should handle the error here
143+
// (for example, log it into a monitoring service)
144+
})
145+
}
103146
}
104147
}
105148
</script>
106149
```
107150

108151
## Server Data Fetching
109152

110-
In `entry-server.js` we can get the components matched by a route with `router.getMatchedComponents()`, and call `asyncData` if the component exposes it. Then we need to attach resolved state to the render context.
153+
In `entry-server.js`, we will set the store state in the render context after the app is finished rendering, thanks to the `context.rendered` hook recognized by the server renderer.
111154

112155
``` js
113156
// entry-server.js
@@ -120,29 +163,17 @@ export default context => {
120163
router.push(context.url)
121164

122165
router.onReady(() => {
123-
const matchedComponents = router.getMatchedComponents()
124-
if (!matchedComponents.length) {
125-
return reject({ code: 404 })
126-
}
127-
128-
// call `asyncData()` on all matched route components
129-
Promise.all(matchedComponents.map(Component => {
130-
if (Component.asyncData) {
131-
return Component.asyncData({
132-
store,
133-
route: router.currentRoute
134-
})
135-
}
136-
})).then(() => {
137-
// After all preFetch hooks are resolved, our store is now
138-
// filled with the state needed to render the app.
166+
// This `rendered` hook is called when the app has finished rendering
167+
context.rendered = () => {
168+
// After the app is rendered, our store is now
169+
// filled with the state from our components.
139170
// When we attach the state to the context, and the `template` option
140171
// is used for the renderer, the state will automatically be
141172
// serialized and injected into the HTML as `window.__INITIAL_STATE__`.
142173
context.state = store.state
174+
}
143175

144-
resolve(app)
145-
}).catch(reject)
176+
resolve(app)
146177
}, reject)
147178
})
148179
}
@@ -153,105 +184,14 @@ When using `template`, `context.state` will automatically be embedded in the fin
153184
``` js
154185
// entry-client.js
155186

156-
const { app, router, store } = createApp()
187+
const { app, store } = createApp()
157188

158189
if (window.__INITIAL_STATE__) {
190+
// We initialize the store state with the data injected from the server
159191
store.replaceState(window.__INITIAL_STATE__)
160192
}
161-
```
162-
163-
## Client Data Fetching
164-
165-
On the client, there are two different approaches for handling data fetching:
166-
167-
1. **Resolve data before route navigation:**
168-
169-
With this strategy, the app will stay on the current view until the data needed by the incoming view has been resolved. The benefit is that the incoming view can directly render the full content when it's ready, but if the data fetching takes a long time, the user will feel "stuck" on the current view. It is therefore recommended to provide a data loading indicator if using this strategy.
170-
171-
We can implement this strategy on the client by checking matched components and invoking their `asyncData` function inside a global route hook. Note we should register this hook after the initial route is ready so that we don't unnecessarily fetch the server-fetched data again.
172-
173-
``` js
174-
// entry-client.js
175-
176-
// ...omitting unrelated code
177-
178-
router.onReady(() => {
179-
// Add router hook for handling asyncData.
180-
// Doing it after initial route is resolved so that we don't double-fetch
181-
// the data that we already have. Using `router.beforeResolve()` so that all
182-
// async components are resolved.
183-
router.beforeResolve((to, from, next) => {
184-
const matched = router.getMatchedComponents(to)
185-
const prevMatched = router.getMatchedComponents(from)
186-
187-
// we only care about non-previously-rendered components,
188-
// so we compare them until the two matched lists differ
189-
let diffed = false
190-
const activated = matched.filter((c, i) => {
191-
return diffed || (diffed = (prevMatched[i] !== c))
192-
})
193-
194-
if (!activated.length) {
195-
return next()
196-
}
197-
198-
// this is where we should trigger a loading indicator if there is one
199193

200-
Promise.all(activated.map(c => {
201-
if (c.asyncData) {
202-
return c.asyncData({ store, route: to })
203-
}
204-
})).then(() => {
205-
206-
// stop loading indicator
207-
208-
next()
209-
}).catch(next)
210-
})
211-
212-
app.$mount('#app')
213-
})
214-
```
215-
216-
2. **Fetch data after the matched view is rendered:**
217-
218-
This strategy places the client-side data-fetching logic in a view component's `beforeMount` function. This allows the views to switch instantly when a route navigation is triggered, so the app feels a bit more responsive. However, the incoming view will not have the full data available when it's rendered. It is therefore necessary to have a conditional loading state for each view component that uses this strategy.
219-
220-
This can be achieved with a client-only global mixin:
221-
222-
``` js
223-
Vue.mixin({
224-
beforeMount () {
225-
const { asyncData } = this.$options
226-
if (asyncData) {
227-
// assign the fetch operation to a promise
228-
// so that in components we can do `this.dataPromise.then(...)` to
229-
// perform other tasks after data is ready
230-
this.dataPromise = asyncData({
231-
store: this.$store,
232-
route: this.$route
233-
})
234-
}
235-
}
236-
})
237-
```
238-
239-
The two strategies are ultimately different UX decisions and should be picked based on the actual scenario of the app you are building. But regardless of which strategy you pick, the `asyncData` function should also be called when a route component is reused (same route, but params or query changed. e.g. from `user/1` to `user/2`). We can also handle this with a client-only global mixin:
240-
241-
``` js
242-
Vue.mixin({
243-
beforeRouteUpdate (to, from, next) {
244-
const { asyncData } = this.$options
245-
if (asyncData) {
246-
asyncData({
247-
store: this.$store,
248-
route: to
249-
}).then(next).catch(next)
250-
} else {
251-
next()
252-
}
253-
}
254-
})
194+
app.$mount('#app')
255195
```
256196

257197
## Store Code Splitting
@@ -289,9 +229,18 @@ We can use `store.registerModule` to lazy-register this module in a route compon
289229
import fooStoreModule from '../store/modules/foo'
290230
291231
export default {
292-
asyncData ({ store }) {
293-
store.registerModule('foo', fooStoreModule)
294-
return store.dispatch('foo/inc')
232+
computed: {
233+
fooCount () {
234+
return this.$store.state.foo.count
235+
}
236+
},
237+
238+
ssrPrefetch () {
239+
return this.fooInc()
240+
},
241+
242+
mounted () {
243+
this.fooInc()
295244
},
296245
297246
// IMPORTANT: avoid duplicate module registration on the client
@@ -300,17 +249,14 @@ export default {
300249
this.$store.unregisterModule('foo')
301250
},
302251
303-
computed: {
304-
fooCount () {
305-
return this.$store.state.foo.count
252+
methods: {
253+
fooInc () {
254+
this.$store.registerModule('foo', fooStoreModule)
255+
return this.$store.dispatch('foo/inc')
306256
}
307257
}
308258
}
309259
</script>
310260
```
311261

312262
Because the module is now a dependency of the route component, it will be moved into the route component's async chunk by webpack.
313-
314-
---
315-
316-
Phew, that was a lot of code! This is because universal data-fetching is probably the most complex problem in a server-rendered app and we are laying the groundwork for easier further development. Once the boilerplate is set up, authoring individual components will be actually quite pleasant.

0 commit comments

Comments
 (0)