Router state not being persisted in react-native with redux
Asked Answered
C

3

17

I have the following redux configuration in react-native using react-native-router-flux and redux-persist. I want to retrieve the last current route on refresh, however the route stack is being overwritten on reload.

This is the reducers/index.js file

import { combineReducers, createStore, applyMiddleware, compose } from 'redux'
import { persistStore, autoRehydrate } from 'redux-persist'
import { AsyncStorage } from 'react-native'
import logger from 'redux-logger'

import { startServices } from '../services'
import navigation from './navigation'
import devices from './devices'
import rooms from './rooms'


import { ActionConst } from 'react-native-router-flux'

function routes (state = {scene: {}}, action = {}) {
  switch (action.type) {
    // focus action is dispatched when a new screen comes into focus
    case ActionConst.FOCUS:
      return {
        ...state,
        scene: action.scene,
      };

    // ...other actions

    default:
      return state;
  }
}

export const reducers = combineReducers({
  routes,
  navigation,
  devices,
  rooms
})

const middleware = [logger()]

const store = createStore(
  reducers,
  compose(
    autoRehydrate(),
    applyMiddleware(...middleware)
  )
)

persistStore(store, {storage: AsyncStorage}, function onStoreRehydrate () {
  startServices()
})

export { store, reducers }

EDIT: This is the index.js with it's Provider and scenes:

import React, { Component } from 'react'
import { store } from './reducers'
import { Provider, connect } from 'react-redux'
import { Router, Scene, Actions } from 'react-native-router-flux';

import Home from './containers/home'
import Login from './containers/login'
import Device from './containers/device'


const scenes = Actions.create(
  <Scene key="root">
      <Scene key="home" component={Home} />
      <Scene key="login" component={Login} />
      <Scene key="device" component={Device} />
  </Scene>
)

const RouterWithRedux = connect()(Router)

export default class EntryPoint extends Component {
  render () {
    return (
      <Provider store={store}>
        <RouterWithRedux scenes={scenes} />
      </Provider>
    )
  }
}
Cimabue answered 16/9, 2016 at 8:50 Comment(0)
M
0

react-native-router-flux doesn't restore a scene by itself even when used with redux. Redux only keeps track of state, so you have to have your app navigate to the previous scene on startup if you want your navigation state to persist.

Assuming you have redux working with react-native-router-flux, all you need to do is connect your app's initial component to redux to get your state and then change your scene to match.

So, in your initial component scene loaded for your app, do something like this at the end to get access to your redux store:

const mapStateToProps = (state) => {
  const { nav } = state

  return {
    currentScene: nav.scene.name,
  }
}

INITIAL_COMPONENT = connect(mapStateToProps)(INITIAL_COMPONENT)

Then in one of your lifecycle methods of that component you could redirect like so:

const { currentScene } = this.props
const initialScene = "Login"

if (currentScene !== initialScene) {
  Actions[currentScene]()
}

You could also pass in props that were used when navigating to the last scene or set a default scene you want to go to if the redux store doesn't have a scene that it's persisting. The app I'm working on is persisting state beautifully now.

Morrill answered 26/4, 2017 at 19:47 Comment(2)
It has to be done in ComponentWillUpdate of the initial scene, which will cause the initial scene to be displayed before it gets transited to the last accessed scene. Is there any way to avoid that?Tropology
I haven't found a way to do avoid that yet, but it most scenarios I've run it in so far, it's not on very long. I'll keep looking for alternatives in the meantime.Morrill
G
0

You need to create your store like this:

const store = createStore(
  reducers,
  compose(
    applyMiddleware(...middleware),
    autoRehydrate(),
  )
);

The autoRehydrate needs to be part of your compose. Check this compose example.

Groundnut answered 22/9, 2016 at 1:31 Comment(3)
I actually have tried that as well. autoRehydrate can behave as well as enhancer.Cimabue
Do you happen to have a repo that I can play around with this?Groundnut
Sorry I do not have a public repo to shareCimabue
L
0

Can you try this I think what happen is the order of the createStore

const enhancers = compose(
  applyMiddleware(...middleware),
  autoRehydrate(),
);

// Create the store with the (reducer, initialState, compose)
const store = createStore(
  reducers,
  {},
  enhancers
);

Or the other solution should be doing it manually with import {REHYDRATE} from 'redux-persist/constants' and call it inside your reducer.

Larisalarissa answered 26/9, 2016 at 12:47 Comment(0)
M
0

react-native-router-flux doesn't restore a scene by itself even when used with redux. Redux only keeps track of state, so you have to have your app navigate to the previous scene on startup if you want your navigation state to persist.

Assuming you have redux working with react-native-router-flux, all you need to do is connect your app's initial component to redux to get your state and then change your scene to match.

So, in your initial component scene loaded for your app, do something like this at the end to get access to your redux store:

const mapStateToProps = (state) => {
  const { nav } = state

  return {
    currentScene: nav.scene.name,
  }
}

INITIAL_COMPONENT = connect(mapStateToProps)(INITIAL_COMPONENT)

Then in one of your lifecycle methods of that component you could redirect like so:

const { currentScene } = this.props
const initialScene = "Login"

if (currentScene !== initialScene) {
  Actions[currentScene]()
}

You could also pass in props that were used when navigating to the last scene or set a default scene you want to go to if the redux store doesn't have a scene that it's persisting. The app I'm working on is persisting state beautifully now.

Morrill answered 26/4, 2017 at 19:47 Comment(2)
It has to be done in ComponentWillUpdate of the initial scene, which will cause the initial scene to be displayed before it gets transited to the last accessed scene. Is there any way to avoid that?Tropology
I haven't found a way to do avoid that yet, but it most scenarios I've run it in so far, it's not on very long. I'll keep looking for alternatives in the meantime.Morrill

© 2022 - 2024 — McMap. All rights reserved.