UNPKG

1.48 kBMarkdownView Raw
1# `@shopify/react-serialize`
2
3[![Build Status](https://travis-ci.org/Shopify/quilt.svg?branch=master)](https://travis-ci.org/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
6Provides 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
16On the server, the `<Serializer />` component will serialize whatever you pass as it's `data` prop.
17
18```javascript
19// in your server renderer
20import {Serializer} from '@shopify/react-serialize';
21
22...
23
24const apolloState = getDatafromTree(appMarkup)
25
26const markup = react.renderToString(
27 <React.Fragment>
28 {appMarkup}
29 <Serializer id="apollo-data" data={apolloState}>
30 </React.Fragment>
31);
32```
33
34Then 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
38import {getSerialized} from '@shopify/react-serialize';
39import ApolloClient from 'apollo-client';
40
41...
42
43const {data: initialApolloData} = getSerialized('apollo-data');
44const client = new ApolloClient({
45 ...myConfig,
46 cache: cache.restore(initialApolloData),
47});
48```