Created
December 16, 2019 21:47
-
-
Save lucianomlima/52097e29d45a4fd35e32631a914afc2d to your computer and use it in GitHub Desktop.
RN react-navigation persistence route filter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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