Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Navigation and Redux Persist

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 ?

like image 391
Kamil Kamili Avatar asked Dec 09 '17 19:12

Kamil Kamili


2 Answers

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)

like image 181
Leo Lei Avatar answered Nov 15 '22 23:11

Leo Lei


In case you're looking to integrate it with react-native-navigation v2, in App.js, make sure you call persistStore() inside the registerAppLaunchedListener() :

import { persistStore } from 'redux-persist';
...
Navigation.events().registerAppLaunchedListener(() => {
  persistStore(store, null, () => {
    Navigation.registerComponentWithRedux(...);
    ...
    Navigation.setRoot({...})
     ...
  })
})
like image 26
Jojo Avatar answered Nov 15 '22 23:11

Jojo