Skip to content

Commit

Permalink
feat: support preload=render
Browse files Browse the repository at this point in the history
  • Loading branch information
sorrycc committed Dec 12, 2024
1 parent 062f3ff commit 29323a9
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions packages/renderer-react/src/link.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { PropsWithChildren } from 'react';
import React, { PropsWithChildren, useLayoutEffect } from 'react';
import { Link, LinkProps } from 'react-router-dom';
import { useAppData } from './appContext';

Expand All @@ -11,9 +11,15 @@ export function LinkWithPrefetch(
>,
) {
const { prefetch: prefetchProp, ...linkProps } = props;
const prefetch = prefetchProp === true ? 'intent' : prefetchProp;
const prefetch =
prefetchProp === true
? 'intent'
: prefetchProp === false
? 'none'
: prefetchProp;
const appData = useAppData();
const to = typeof props.to === 'string' ? props.to : props.to?.pathname;
const hasRenderFetched = React.useRef(false);

const handleMouseEnter = (e: React.MouseEvent<HTMLAnchorElement>) => {
if (prefetch !== 'intent') return;
Expand All @@ -38,6 +44,13 @@ export function LinkWithPrefetch(
}
};

useLayoutEffect(() => {
if (prefetch === 'render' && !hasRenderFetched.current) {
appData.preloadRoute?.(to!);
hasRenderFetched.current = true;
}
}, [prefetch, to]);

// compatible with old code
// which to might be undefined
if (!to) return null;
Expand Down

0 comments on commit 29323a9

Please sign in to comment.