Skip to content

Commit

Permalink
allow controlling prefetch behavior of Form
Browse files Browse the repository at this point in the history
  • Loading branch information
lubieowoce committed Jul 29, 2024
1 parent 0184b34 commit 72a6979
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions packages/next/src/client/form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,19 @@ export type FormProps = {
* - If `action` is a function, it will be called when the form is submitted. See the [React docs](https://react.dev/reference/react-dom/components/form#props) for more.
*/
action: NonNullable<HTMLFormProps['action']>
/**
* Controls how the route specified by `action` is prefetched.
* Any `<Form />` that is in the viewport (initially or through scroll) will be prefetched.
* Prefetch can be disabled by passing `prefetch={false}`. Prefetching is only enabled in production.
*
* In App Router:
* - `null` (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data.
* - `true`: This will prefetch the full React Server Component data for all route segments, regardless of whether they contain a segment with `loading.js`.
* - `false`: This will not prefetch any data.
*
* @defaultValue `null`
*/
prefetch?: boolean | null
/**
* Whether submitting the form should replace the current `history` state instead of adding a new url into the stack.
* Only valid if `action` is a string.
Expand All @@ -40,6 +53,7 @@ export type FormProps = {
export default function Form({
replace,
scroll,
prefetch = null,
ref: externalRef,
...props
}: FormProps) {
Expand Down Expand Up @@ -78,18 +92,23 @@ export default function Form({
return
}

if (!isVisible) {
const isPrefetchEnabled = prefetch !== false

if (!isVisible || !isPrefetchEnabled) {
return
}

const prefetchKind =
prefetch === null ? PrefetchKind.AUTO : PrefetchKind.FULL

try {
// TODO: do we need to take the current field values here?
// or are we assuming that queryparams can't affect this (but what about rewrites)?
router.prefetch(actionProp, { kind: PrefetchKind.AUTO })
router.prefetch(actionProp, { kind: prefetchKind })
} catch (err) {
console.error(err)
}
}, [isNavigatingForm, isVisible, actionProp, router])
}, [isNavigatingForm, isVisible, actionProp, prefetch, router])

if (!isNavigatingForm) {
if (process.env.NODE_ENV === 'development') {
Expand Down

0 comments on commit 72a6979

Please sign in to comment.