1

I have store config.autologin properties with Redux-persist. When I create a React-navigation stack, I'd like to check autoloign value, but at this time the state isn't rehydrated yet. I supposed that PersistGate is what I need, but this ins't true. Can you help me? Thanks

App.js

export default class App extends React.Component {
  render() {
    return (
      <Provider store={reduxStore}>
        <PersistGate loading={null} persistor = {persistor}>
          <AppContainer
            ref={navigatorRef => {
              NavigationService.setTopLevelNavigator(navigatorRef);
            }}
          />
        </PersistGate>
      </Provider>
    );
  }
}

reduxStore

const persistState = {
    key: 'root',
    storage,
    whitelist: ['config']
}

const persistedReducer = persistReducer(persistState, reducers)
export const reduxStore = createStore(persistedReducer, devToolsEnhancer({ realtime: true }))
export const persistor = persistStore(reduxStore)

AppNavigation

selectInitialRoute = () =>{
    if(reduxStore.getState().config.autoLogin)
        return 'DrawerStack'
    else
        return 'Home'
}

const defaultNavigation = createStackNavigator({
    Home: loginNavigation,
    DrawerStack: defaultDrawerNavigation
}, {
    initialRouteName: this.selectInitialRoute(),
    defaultNavigationOptions: {
        header: null
    },
}
)

const AppContainer = createAppContainer(defaultNavigation);

export default AppContainer

1 Answer 1

3

I have a similar situation in my app. I have two drawers: LoggedDrawer and UnloggedDrawer and I need to check before initializing them if the user is logged on/off to show the specific drawer for each state.

You probably can see that the state is correctly updated in your render method. If you want to get this status beforehand you'll need getDerivedStateFromProps

I believe that in your case it would go something like this:

static getDerivedStateFromProps(nextProps, prevState) {
  if(nextProps.autoLogin !== prevState.autoLogin) {
    return 'Home'
  } else {
    return 'DrawerStack'
  }
}

So you would have the state from your redux(nextProps) and your prevState(the state from the component), then you'll check if they are different and then act accordingly.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.