1 | # `@shopify/react-serialize`
|
2 |
|
3 | [![CircleCI](https://circleci.com/gh/Shopify/quilt.svg?style=svg&circle-token=8dafbec2d33dcb489dfce1e82ed37c271b26aeba)](https://circleci.com/gh/Shopify/quilt)
|
4 | [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE.md) [![npm version](https://badge.fury.io/js/%40shopify%2Freact-serialize.svg)](https://badge.fury.io/js/%40shopify%2Freact-serialize) ![npm bundle size (minified + gzip)](https://img.shields.io/bundlephobia/minzip/@shopify/react-serialize.svg)
|
5 |
|
6 | Provides an idiomatic way to serialize data for rehydration in a universal react application.
|
7 |
|
8 | ## Installation
|
9 |
|
10 | ```bash
|
11 | $ yarn add @shopify/react-serialize
|
12 | ```
|
13 |
|
14 | ## Usage
|
15 |
|
16 | On the server, the `<Serializer />` component will serialize whatever you pass as it's `data` prop.
|
17 |
|
18 | ```javascript
|
19 | // in your server renderer
|
20 | import {Serializer} from '@shopify/react-serialize';
|
21 |
|
22 | ...
|
23 |
|
24 | const apolloState = getDatafromTree(appMarkup)
|
25 |
|
26 | const markup = react.renderToString(
|
27 | <React.Fragment>
|
28 | {appMarkup}
|
29 | <Serializer id="apollo-data" data={apolloState}>
|
30 | </React.Fragment>
|
31 | );
|
32 | ```
|
33 |
|
34 | Then on the client, you can use `getSerialized` to fetch that data out of the DOM and initialize whatever you need.
|
35 |
|
36 | ```javascript
|
37 | // when you are rehydrating on the client
|
38 | import {getSerialized} from '@shopify/react-serialize';
|
39 | import ApolloClient from 'apollo-client';
|
40 |
|
41 | ...
|
42 |
|
43 | const {data: initialApolloData} = getSerialized('apollo-data');
|
44 | const client = new ApolloClient({
|
45 | ...myConfig,
|
46 | cache: cache.restore(initialApolloData),
|
47 | });
|
48 | ```
|