Skip to content

Instantly share code, notes, and snippets.

@shokimble
Created February 26, 2018 04:16
Show Gist options
  • Save shokimble/3b9ec98499cc9d35ab1a5437a046c761 to your computer and use it in GitHub Desktop.
Save shokimble/3b9ec98499cc9d35ab1a5437a046c761 to your computer and use it in GitHub Desktop.
/*
//You should already have initialised your stack navigator and named it AppNavigator (you can call it something else just change all the references)
//eg.
const AppNavigator = StackNavigator(
Routes
);
*/
//we're saving the default getStateForAction
const prevGetStateForAction = AppNavigator.router.getStateForAction;
AppNavigator.router = {
...AppNavigator.router,
getStateForAction(action, state) {
//check if route is already on stack and go to it instead of adding a new item on stack
//NOTE: This will break things like being able to have push notification messages on the same route but different messages and being able to go back through them
//if that becomes a problem just opt out for certain route names eg if(action.routeName == "Messages") return prevGetStateForAction(aciton,state)
if(state && action.type == 'Navigation/NAVIGATE' && state.routes !== undefined ) {
//console.log("getStateForAction state",state,"action,",action);
var i = -1;
//try find the route in the stack
for(var c =0; c < state.routes.length; c++) {
if(state.routes[c].routeName == action.routeName) {
i = c;
break;
}
}
//found it but we're already there so do nothing as we're trying to navigate to ourselves
if(i == state.index) {
console.log("getstateforaction() - you're trying to navigate to yourself!");
return null;
}
//didn't find it - add screen to stack - ie call default action
if(i == -1) {
console.log("getstateforaction() - no duplicate screen found");
return prevGetStateForAction(action,state);
}
//found it - move it to just after index and increment index - i think
console.log("stacknavigator is trying to duplicate route - moving back to previous route");
var route = state.routes[i];
var routes = state.routes;
routes.splice(i,1);
routes = [
...routes,
route
];
newIndex = routes.length-1;
return {
...state,
routes: routes,
index: newIndex
}
}
return prevGetStateForAction(action,state);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment