From 9ff483a554bc8e51602526918b52d534209a08a6 Mon Sep 17 00:00:00 2001 From: "satyajit.happy" Date: Mon, 29 Jul 2019 00:59:11 +0200 Subject: [PATCH] fix: adjust index when route names are changed --- example/StackNavigator.tsx | 7 ++++++- example/TabNavigator.tsx | 19 +++++++++++-------- src/__tests__/__fixtures__/MockRouter.tsx | 7 ++++++- src/__tests__/index.test.tsx | 2 +- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/example/StackNavigator.tsx b/example/StackNavigator.tsx index bc5dac85..9916fe70 100644 --- a/example/StackNavigator.tsx +++ b/example/StackNavigator.tsx @@ -107,10 +107,15 @@ function StackRouter(options: DefaultRouterOptions) { }, getStateForRouteNamesChange(state, { routeNames }) { + const routes = state.routes.filter(route => + routeNames.includes(route.name) + ); + return { ...state, routeNames, - routes: state.routes.filter(route => routeNames.includes(route.name)), + routes, + index: Math.min(state.index, routes.length - 1), }; }, diff --git a/example/TabNavigator.tsx b/example/TabNavigator.tsx index 226a0545..eb6105db 100644 --- a/example/TabNavigator.tsx +++ b/example/TabNavigator.tsx @@ -91,17 +91,20 @@ function TabRouter(options: DefaultRouterOptions) { }, getStateForRouteNamesChange(state, { routeNames, routeParamList }) { + const routes = routeNames.map( + name => + state.routes.find(r => r.name === name) || { + name, + key: `${name}-${shortid()}`, + params: routeParamList[name], + } + ); + return { ...state, routeNames, - routes: routeNames.map( - name => - state.routes.find(r => r.name === name) || { - name, - key: `${name}-${shortid()}`, - params: routeParamList[name], - } - ), + routes, + index: Math.min(state.index, routes.length - 1), }; }, diff --git a/src/__tests__/__fixtures__/MockRouter.tsx b/src/__tests__/__fixtures__/MockRouter.tsx index 37bb56d7..68a5a164 100644 --- a/src/__tests__/__fixtures__/MockRouter.tsx +++ b/src/__tests__/__fixtures__/MockRouter.tsx @@ -46,10 +46,15 @@ export default function MockRouter(options: DefaultRouterOptions) { }, getStateForRouteNamesChange(state, { routeNames }) { + const routes = state.routes.filter(route => + routeNames.includes(route.name) + ); + return { ...state, routeNames, - routes: state.routes.filter(route => routeNames.includes(route.name)), + routes, + index: Math.min(state.index, routes.length - 1), }; }, diff --git a/src/__tests__/index.test.tsx b/src/__tests__/index.test.tsx index ce851b46..3e6634f1 100644 --- a/src/__tests__/index.test.tsx +++ b/src/__tests__/index.test.tsx @@ -494,7 +494,7 @@ it('handles change in route names', () => { ); expect(onStateChange).toBeCalledWith({ - index: 1, + index: 0, key: '0', routeNames: ['foo', 'baz', 'qux'], routes: [{ key: 'foo', name: 'foo' }],