noah.plus

apollo-cache-redux を使って Apollo Client を Redux に統合する

2018-10-21

apollo-cache-redux を使って、Apollo Clientのキャッシュ機能そのままに Redux に統合する。

rportugal/apollo-cache-redux

一連のコードは以下の通り。

// src/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import ApolloClient from 'apollo-boost';
import {ApolloProvider} from 'react-apollo';
import {ReduxCache, apolloReducer} from 'apollo-cache-redux';
import App from './App';

const store = createStore(
    combineReducers({
        apollo: apolloReducer
        ...otherReducers
    })
);

const cache = new ReduxCache({
    store,
    dataIdFromObject: object => object.__typename || null
});

const client = new ApolloClient({
    uri: 'https://api.github.com/graphql',
    headers: {
        authorization: 'bearer PUT_YOUR_TOKEN_HERE'
    },
    cache
});

ReactDOM.render(
    <ApolloProvider client={client}>
        <Provider store={store}>
            <App/>
        </Provider>
    </ApolloProvider>,
    document.getElementById('root')
);

ポイント毎にざっくりと説明していく。

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import ApolloClient from 'apollo-boost';
import {ApolloProvider} from 'react-apollo';
import {ReduxCache, apolloReducer} from 'apollo-cache-redux';
import App from './App';

まずはインポート部分について。今回は簡単にセットアップをするために apollo-boost を使用している。これは apollo の初期設定を良い感じにやってくれるものなので、普通に apollo-client を使って自分で設定をしても可。

そして今回の主役である apollo-cache-redux から ReduxCacheapolloReducer をインポートしている。

const store = createStore(
    combineReducers({
        apollo: apolloReducer
        ...otherReducers
    })
);

Redux Storeの作成部分。ここで先ほどインポートした apolloReducer とその他の reducer を組み合わせている。...otherReducers の部分には必要に応じて apolloReducer 以外の reducer を追加する。

const cache = new ReduxCache({
    store,
    dataIdFromObject: object => object.__typename || null
});

const client = new ApolloClient({
    uri: 'https://api.github.com/graphql',
    headers: {
        authorization: 'bearer PUT_YOUR_TOKEN_HERE'
    },
    cache
});

ReduxCache で名前通り Redux に統合できる形で apollo-client によるキャッシュを作成できるようにする。

なお、apollo-cache-redux の ReduxCacheapollo-client のInMemoryCache と互換性があるので、InMemoryCache同じ設定をすることができる。

上記の例では、__typename がオブジェクトの key になるように Normalization を行っている。Normalization に関しては apollo の公式ドキュメントが詳しい。

ReactDOM.render(
    <ApolloProvider client={client}>
        <Provider store={store}>
            <App/>
        </Provider>
    </ApolloProvider>,
    document.getElementById('root')
);

最後に Provider の部分。一番外側にapollo、その内側に Redux のProviderを配置して完成。


noah.plus