Created
September 21, 2021 16:13
-
-
Save jaimeagudo/ab8f0bcf700b8bcb73645c21c86a3ee4 to your computer and use it in GitHub Desktop.
usePrefetchRoute proposal
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
// @flow | |
import { useCallback } from 'react'; | |
import { useDispatch } from 'react-redux'; | |
import * as routePaths from '~/constants/routes'; | |
import { GET_SMART_CHARGING } from '~/state/products/ev-charger/actions'; | |
const ROUTES_PREFETCH_ACTIONS = { | |
[routePaths.evChargerSettings]: { | |
type: GET_SMART_CHARGING, | |
routeArgsToActionPayload: ({ id, ...restOfNavigationArguments }) => ({ deviceId: id }), | |
}, | |
}; | |
export function usePrefetchRoute(route: string, passProps?: Object, options?: Object) { | |
const dispatch = useDispatch(); | |
const { type, routeArgsToPayload } = ROUTES_PREFETCH_ACTIONS[route]; | |
const payload = routeArgsToPayload(passProps); | |
return useCallback(() => { | |
dispatch({ type, payload }); | |
}, [dispatch, payload, type]); | |
} | |
//////////////////////////////////////////////////////////////////////// | |
// Usage example: on any screen previous to the target one where we'll need the data to be available: | |
const prefetchMyRoute = usePrefetchRoute(routePaths.evChargerSettings, { id: 'example-id' }); | |
prefetchMyRoute(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment