feat: add ability to dispatch a update function

This commit is contained in:
satyajit.happy
2019-06-12 00:08:57 +02:00
parent 1c394e1279
commit 720a90bd5f
2 changed files with 12 additions and 5 deletions

View File

@@ -99,9 +99,12 @@ export type NavigationHelpers<
ParamList extends ParamListBase = ParamListBase ParamList extends ParamListBase = ParamListBase
> = { > = {
/** /**
* Dispatch an action to the router. * Dispatch an action or an update function to the router.
* The update function will receive the current state,
*/ */
dispatch(action: NavigationAction): void; dispatch(
action: NavigationAction | ((state: NavigationState) => NavigationState)
): void;
/** /**
* Navigate to a route in current navigation tree. * Navigate to a route in current navigation tree.

View File

@@ -180,8 +180,12 @@ export default function useNavigationBuilder(
); );
const helpers = React.useMemo((): NavigationHelpers => { const helpers = React.useMemo((): NavigationHelpers => {
const dispatch = (action: NavigationAction) => { const dispatch = (
if (!onAction(action)) { action: NavigationAction | ((state: NavigationState) => NavigationState)
) => {
if (typeof action === 'function') {
setState(action(getState()));
} else if (!onAction(action)) {
throw new Error( throw new Error(
`No navigators are able to handle the action "${action.type}".` `No navigators are able to handle the action "${action.type}".`
); );
@@ -206,7 +210,7 @@ export default function useNavigationBuilder(
), ),
dispatch, dispatch,
}; };
}, [onAction, parentNavigationHelpers, router.actionCreators]); }, [getState, onAction, parentNavigationHelpers, router, setState]);
const navigation = React.useMemo( const navigation = React.useMemo(
() => ({ () => ({