Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo with redux-persist

I integrated react-apollo for fetching data from my GraphQL server into my react native application. I use redux-perist for persisting and rehydrating the redux store.

But I don't know how to rehydrate my apollo state.

Anyone know how I can do that?

Thanks

like image 968
Carolina Avatar asked Oct 17 '22 14:10

Carolina


1 Answers

You can use the autoRehydrate feature of redux-persist. It will asyncronously run an action with type REHYDRATE that will rehydrate all stores unless you blacklist them.

If you try to execute a query that was previously executed, Apollo will check your Redux store first and you should see an APOLLO_QUERY_RESULT_CLIENT action execute (meaning it's returning from the client store instead of querying the server). You can modify the fetchPolicy to specify how the query gets its data (network only, cache first, etc.)

Here's a basic setup:

import React, { Component } from 'react';
import { ApolloProvider } from 'react-apollo';
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { persistStore, autoRehydrate } from 'redux-persist';
import { AsyncStorage } from 'react-native';

const networkInterface = createNetworkInterface({ uri: 'http://localhost:8080/graphql' });

export const client = new ApolloClient({
  networkInterface: networkInterface,
});

const store = createStore(
  combineReducers({
    apollo: client.reducer(),
  }),
  {}, // initial state
  compose(
    applyMiddleware(client.middleware()),
    autoRehydrate(),
  ),
);

// persistent storage
persistStore(store, {
  storage: AsyncStorage, // or whatever storage you want
});

export default class App extends Component {
  render() {
    return (
      <ApolloProvider store={store} client={client}>
        <YourApp />
      </ApolloProvider>
    );
  }
}
like image 133
srtucker22 Avatar answered Oct 21 '22 08:10

srtucker22