react-native-navigation icon indicating copy to clipboard operation
react-native-navigation copied to clipboard

Using redux-persist gate in react-native-navigation

Open nimabk82 opened this issue 8 years ago • 23 comments

how to use PersistGate from redux-persist.

nimabk82 avatar Sep 05 '18 10:09 nimabk82

i think RNN team should make registerComponentWithRedux expandable to support persist gate

ammoradi avatar Sep 08 '18 11:09 ammoradi

@nimamyscreen

  • RNN v1: please refer https://github.com/wix/react-native-navigation/blob/9d4eea835ad83170c39c336c108ef2610c078f19/docs/third-party-libraries-support.md#redux-persist

  • RNN v2: please refer https://github.com/wix/react-native-navigation/issues/3590#issuecomment-406798029

phuongwd avatar Sep 10 '18 05:09 phuongwd

@phuongwd i saw these comments. but they are not an official solution. for me, app crashed with these solutions !

ammoradi avatar Sep 10 '18 09:09 ammoradi

@ammoradi This is a snippet of my index.js. I wait till RNN is ready and my store is persisted. This way there is no need for a persistGate since the store is already filled when it gets used.

import { Navigation } from 'react-native-navigation';
import { Provider } from 'react-redux';
import { persistStore } from 'redux-persist';

// import store from 'PATH_TO_YOUR_STORE';

/**
 * Resolves when the store is succesfully rehydrated.
 * @param {store} storeToHydrate - The store to rehydrate
 * @returns {Promise} - Returns a promise that resolves when the store is hydrated.
 */
const rehydrateStore = storeToHydrate => new Promise((resolve) => {
  persistStore(storeToHydrate, undefined, () => {
    resolve();
  });
});

/**
 * Wait till RNN navigation is ready.
 * @returns {Promise} - Resolves when RNN navigation has fully launched
 */
const onNavigationReady = () => new Promise((resolve) => {
  Navigation.events().registerAppLaunchedListener(() => {
    resolve();
  });
});

/**
 * Async function that bootstraps our application
 * Registers screens ->
 *      Wait for store to hydrate
 *      Wait for Navigation to be ready
 *      Wait for icons to be loaded
 * Then set our layout according to user's logged in state.
 */
async function bootstrap() {
  registerScreens(Provider, store);
  await Promise.all([rehydrateStore(store), onNavigationReady()]);
// RNN is ready, store is filled
// Now show layout according to state.
}

bootstrap();

ItsNoHax avatar Sep 10 '18 11:09 ItsNoHax

@ItsNoHax thanks for your responsibility. I will test your solution :)

ammoradi avatar Sep 10 '18 12:09 ammoradi

@ItsNoHax can you share your registerScreens() please ?

devjaw avatar Sep 12 '18 16:09 devjaw

@devjaw i think he meant registerComponentWithRedux(name, component, provider, store)

ammoradi avatar Sep 12 '18 17:09 ammoradi

@ammoradi i tried to use this solution but it doesn't work with me and also there is no error in my app. it just stuck on blank white screen

devjaw avatar Sep 13 '18 05:09 devjaw

@devjaw happening to me as well, it works fine on iOS but on android redux-persist getting error on rehydrating. i switched to redux storage, worked fine

damathryx avatar Sep 16 '18 00:09 damathryx

@ItsNoHax there is one strange thing on Android: if you exit app via back button, and then open application, registerAppLaunchedListener event is fired, but not persistStore callback. persistStore in this case is already loaded

talyuk avatar Sep 17 '18 14:09 talyuk

Yeah, happens in Debug mode @talyuk. Not sure why

ItsNoHax avatar Sep 18 '18 14:09 ItsNoHax

@ItsNoHax I have white screen on IOS await Promise.all([rehydrateStore(store), onNavigationReady()]); rehydrateStore(store) is never resolved

rendomnet avatar Sep 27 '18 06:09 rendomnet

I had a similar problem with Mobx as well. If you use any async function to do anything before the first screen is registered, the app wouldn't start only on Android while IOS works fine.

jinshin1013 avatar Sep 29 '18 04:09 jinshin1013

Can anyone show your store file?

rendomnet avatar Sep 29 '18 04:09 rendomnet

Here is a little example project: https://github.com/ItsNoHax/EventFinder

ItsNoHax avatar Oct 03 '18 14:10 ItsNoHax

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If you believe the issue is still relevant, please test on the latest Detox and report back. Thank you for your contributions.

stale[bot] avatar Nov 26 '18 13:11 stale[bot]

Closing this as the solutions here including mine are bad. The listener for RNN's startup should always be available so that it can also handle Android back button.

My working solution is the following:

import { Navigation } from 'react-native-navigation';
import { persistStore as persistStoreRaw } from 'redux-persist';
import store from './src/store/store';
import { loadIcons } from './src/lib/AppIcons';
import { registerScreens } from './src/screens/screens';
import { setInitialLayout } from './src/NavigationController';


/**
 * Wait till our store is persisted
 * @param {store} storeToPersist - The redux store to persist
 * @returns {Promise} - Promise that resolves when the store is rehydrated
 */
const persistStore = storeToPersist => new Promise((resolve) => {
  persistStoreRaw(storeToPersist, undefined, () => {
    resolve();
  });
});

/**
 * We register screens
 *  then we wait for
 *    - Store to be rehydrated
 *    - Icons to be loaded.
 * and then we finally initialize
 * layout accordingly.
 */
async function bootstrap() {
  registerScreens(store);

  await Promise.all([loadIcons(), persistStore(store)]);

  setInitialLayout();
}

/**
 * The initial listener of our app,
 * this will get triggered on app start or when
 * the Android activity is recreated.
 * (For example by pressing back button on the
 * root screen)
 */
Navigation.events().registerAppLaunchedListener(() => {
  bootstrap();
});

ItsNoHax avatar Dec 01 '18 16:12 ItsNoHax

@ItsNoHax please reopen this issue. there is not yet any official way to do this!

ammoradi avatar Dec 03 '18 19:12 ammoradi

@ammoradi There will never be official support for Redux, the plan is to keep the navigation open to all sort of data management solutions.

ItsNoHax avatar Dec 04 '18 09:12 ItsNoHax

No need to do anything fancy with promises simply create store as described in redux-persist docs then in index.js file add a wrapper function on every screen like this.

/** @format */

// import {AppRegistry} from 'react-native'; // import App from './App'; // import {name as appName} from './app.json';

// AppRegistry.registerComponent(appName, () => App); // // import {Navigation} from "react-native-navigation";

import themeConstants from "./src/theme"; import {componentIds, screenNames} from "./src/screens"; import { PersistGate } from 'redux-persist/integration/react' import TodoList from "./src/screens/ToDo/ToDo"; import CommentsScreen from "./src/screens/ToDo/commentsScreen"; import {persistStore} from "redux-persist"; import {Provider} from "react-redux"; import store from "./src/store/createStore/createStore"; import React from "react"; import {AsyncStorage} from "react-native"; import {Platform, ActivityIndicator} from "react-native";

//let persistor = persistStore(store().store)

const TodoListWithStore = (props) => {
  return (
      <PersistGate loading={null} persistor={store().persistor}>
        <TodoList {...props}/>
      </PersistGate>
  );
};

const Loading = () => { return ( <ActivityIndicator size={"large"} animating /> ); }; const CommentsScreenWithStore = (props) => {

    return (
        <Provider store={store().store}>
        <PersistGate loading={Loading()} persistor={store().persistor}>
          <CommentsScreen {...props}/>
        </PersistGate>
        </Provider>
    );


};
Navigation.registerComponentWithRedux(screenNames.toDo, () => TodoListWithStore, Provider, store().store);
Navigation.registerComponentWithRedux(screenNames.commentsScreen, () => CommentsScreenWithStore, Provider, store().store);

/* topBar: { visible: true, animate: true, hideOnScroll: true, buttonColor: themeConstants.pink800, backButton: { color: themeConstants.pink400 }, background: { color: themeConstants.primary }, title: { color: themeConstants.offWhite, fontSize: 18, alignment: "center" } */

Navigation.setDefaultOptions({
    topBar: {
      title: {
        ...Platform.select({
          ios: { fontFamily: 'System', },
          android: { fontFamily: 'Roboto' }
        }),
        color: '#262626',
        alignment: 'center',
      },
      alignment: 'center',
      elevation: 0,
      noBorder: true,
      drawBehind: true,
      background: {
        color: 'transparent'
      }
  },
  statusBar: {
    visible: true,
    style: "light",
    backgroundColor: themeConstants.primary
  },
  layout: {
    backgroundColor: themeConstants.light,
    orientation: ["portrait"] //["portrait", "landscape"] An array of supported orientations
  },
  bottomTabs: {
    visible: true,
    animate: true, // Controls whether BottomTabs visibility changes should be animated
    backgroundColor: themeConstants.secondary
  },
  bottomTab: {
    iconColor: themeConstants.tertiary,
    selectedIconColor: themeConstants.pink400,
    textColor: themeConstants.tertiary,
    selectedTextColor: themeConstants.pink400,
    fontFamily: "Helvetica",
    fontSize: 10
  }
});

const stack = { children: [ { component: { id: componentIds.toDoStack, name: screenNames.toDo, passProps: {} } } ], options: {} }; Navigation.events().registerAppLaunchedListener(() => { Navigation.setRoot({ root: { stack: stack } }); });

RajenderDandyal avatar Dec 30 '18 12:12 RajenderDandyal