React Native Navigation and Redux Persist

Kamil Kamili picture Kamil Kamili · Dec 9, 2017 · Viewed 9.6k times · Source

I am trying to integrate redux-persist with wix react-native-navigation. However, I am unable to find any examples or documentation stating the boilerplate code needed to integrate the both libraries.

I was wondering if anyone would like to share their solution if they have solved this issue ?

Answer

Leo Lei picture Leo Lei · Jan 1, 2018

First of all, the basic setup should be the similar with or without react-native-navigation as described in the documentation in store.js:

import { persistStore, persistCombineReducers } from 'redux-persist'
import storage from 'redux-persist/es/storage' // default: 
localStorage if web, AsyncStorage if react-native
import reducers from './reducers' // where reducers is an object of 
reducers

const config = {
  key: 'root',
  storage,
}

const reducer = persistCombineReducers(config, reducers)

function configureStore () {
  // ...
  let store = createStore(reducer)
  return store

  // We'll skip persistStore for now
  // let persistor = persistStore(store)
  //return { persistor, store }
}

The persistStore call is commented out as we'll do it below. The persistStore method takes a callback in its third argument. The callback is executed after the state is restored/rehydrated. This is nice because this means we can delay starting the screen(s) until the state is rehydrated.

Let's assume you have the following bootstrap code in App.js:

store = configureStore()

registerScreens(store, Provider)

Navigation.startTabBasedApp({
  tabs: [{...},]
})

Now we can add persistStore and wrap your bootstrap code in it like this:

store = configureStore()

persistStore(store, null, () => {
  registerScreens(store, Provider)

  Navigation.startTabBasedApp({
    tabs: [{...},]
  })
})

Note: In v4, you pass config instead of null: persistStore(store, config, callback)