Skip to content

Instantly share code, notes, and snippets.

@lucianomlima
Created December 16, 2019 21:47
Show Gist options
  • Save lucianomlima/52097e29d45a4fd35e32631a914afc2d to your computer and use it in GitHub Desktop.
Save lucianomlima/52097e29d45a4fd35e32631a914afc2d to your computer and use it in GitHub Desktop.
RN react-navigation persistence route filter
import type { NavigationState } from 'react-navigation';
type RoutesList = Array<string>;
type PersistenceFunctions = {
persistNavigationState: () => void,
loadNavigationState: () => void,
};
const PERSISTENCE_KEY = 'NavigationState';
function findRouteInList({ index, routes }: NavigationState, routeKeys: RoutesList): boolean {
return routes[index].routes.findIndex(({ key }) => routeKeys.includes(key)) !== -1;
}
function haveAllowedRoutes(state: NavigationState, allowedRoutes: RoutesList = []): boolean {
if (allowedRoutes.length) {
return findRouteInList(state, allowedRoutes);
}
return false;
}
export function clearNavigationState(): void {
AsyncStorage.removeItem(PERSISTENCE_KEY);
}
const persistNavigationState = (allowedRoutes: RoutesList) => (navState: NavigationState): void => {
if (__DEV__ || haveAllowedRoutes(navState, allowedRoutes)) {
AsyncStorage.setItem(PERSISTENCE_KEY, JSON.stringify(navState));
}
};
const loadNavigationState = async (): NavigationState => {
const jsonString = await AsyncStorage.getItem(PERSISTENCE_KEY);
return JSON.parse(jsonString);
};
export const getPersistenceProps = (
allowedRoutesInProduction: RoutesList = []
): PersistenceFunctions => ({
persistNavigationState: persistNavigationState(allowedRoutesInProduction),
loadNavigationState,
});
import { getPersistenceProps } from './persistence';
const routes = {
home: 'Home',
login: 'Login',
signup: 'SingUp',
};
const allowedPersistentRoutes = [
routes.home,
routes.login,
];
export default class RootNavigation extends React.Component {
navigator: React.createRef();
componentDidMount() {
NavigationService.setTopLevelNavigator(this.navigator.current);
}
render() {
return <AppContainer ref={this.navigator} {...getPersistenceProps(allowedPersistentRoutes)} />;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment