Skip to content

Instantly share code, notes, and snippets.

@jaimeagudo
Created September 21, 2021 16:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaimeagudo/ab8f0bcf700b8bcb73645c21c86a3ee4 to your computer and use it in GitHub Desktop.
Save jaimeagudo/ab8f0bcf700b8bcb73645c21c86a3ee4 to your computer and use it in GitHub Desktop.
usePrefetchRoute proposal
// @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