Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fizz] Recover from errors thrown by progressive enhancement form generation #28611

Merged
merged 1 commit into from
Mar 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 36 additions & 11 deletions packages/react-dom-bindings/src/server/ReactFizzConfigDOM.js
Original file line number Diff line number Diff line change
Expand Up @@ -1045,14 +1045,43 @@ function pushAdditionalFormField(

function pushAdditionalFormFields(
target: Array<Chunk | PrecomputedChunk>,
formData: null | FormData,
formData: void | null | FormData,
) {
if (formData !== null) {
if (formData != null) {
// $FlowFixMe[prop-missing]: FormData has forEach.
formData.forEach(pushAdditionalFormField, target);
}
}

function getCustomFormFields(
resumableState: ResumableState,
formAction: any,
): null | ReactCustomFormAction {
const customAction = formAction.$$FORM_ACTION;
if (typeof customAction === 'function') {
const prefix = makeFormFieldPrefix(resumableState);
try {
return formAction.$$FORM_ACTION(prefix);
} catch (x) {
if (typeof x === 'object' && x !== null && typeof x.then === 'function') {
// Rethrow suspense.
throw x;
}
// If we fail to encode the form action for progressive enhancement for some reason,
// fallback to trying replaying on the client instead of failing the page. It might
// work there.
if (__DEV__) {
// TODO: Should this be some kind of recoverable error?
console.error(
'Failed to serialize an action for progressive enhancement:\n%s',
x,
);
}
}
}
return null;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What was the old behavior if processReply errored? These changes make sense for the stated use case but could processReply error in a way where we wouldn't want the client action wait for hydration style treatement on SSR?

Copy link
Collaborator Author

@sebmarkbage sebmarkbage Mar 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It used to just error the SSR render - which itself is just a client-render to recover so not really that different.

The nice thing about that is that if your previous state or closure contains something non-serializable it would give you an early hint that IF you submitted the form it would error. Now that happens after submitting.

In principle we could in DEV or something eagerly serialize these on the client to see if it would've failed on the client too early.

But in general it's just going to error when you try to invoke the form instead.

However, since most things with temporary references is serializable anyway we don't really error for anything other than if like a promise we're trying to serialize rejects (which should arguably error on the server instead as discussed before - if we wanted to support streaming replies). More likely the server will error when you try to inspect a Reference.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we brand the temporaryReferenceSet errors so we can treat them passively like this but let the other errors error the SSR render?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Other than the promise thing - which should probably be serialized as an error instead. Any other error is really a bug in the serialization and it seems better to fallback in that case anyway.

Regardless it seems like it's better in production to fallback to client handling just for the form than client handling for the whole page.

}

function pushFormActionAttribute(
target: Array<Chunk | PrecomputedChunk>,
resumableState: ResumableState,
Expand All @@ -1062,7 +1091,7 @@ function pushFormActionAttribute(
formMethod: any,
formTarget: any,
name: any,
): null | FormData {
): void | null | FormData {
let formData = null;
if (enableFormActions && typeof formAction === 'function') {
// Function form actions cannot control the form properties
Expand Down Expand Up @@ -1092,12 +1121,10 @@ function pushFormActionAttribute(
);
}
}
const customAction: ReactCustomFormAction = formAction.$$FORM_ACTION;
if (typeof customAction === 'function') {
const customFields = getCustomFormFields(resumableState, formAction);
if (customFields !== null) {
// This action has a custom progressive enhancement form that can submit the form
// back to the server if it's invoked before hydration. Such as a Server Action.
const prefix = makeFormFieldPrefix(resumableState);
const customFields = formAction.$$FORM_ACTION(prefix);
name = customFields.name;
formAction = customFields.action || '';
formEncType = customFields.encType;
Expand Down Expand Up @@ -1882,12 +1909,10 @@ function pushStartForm(
);
}
}
const customAction: ReactCustomFormAction = formAction.$$FORM_ACTION;
if (typeof customAction === 'function') {
const customFields = getCustomFormFields(resumableState, formAction);
if (customFields !== null) {
// This action has a custom progressive enhancement form that can submit the form
// back to the server if it's invoked before hydration. Such as a Server Action.
const prefix = makeFormFieldPrefix(resumableState);
const customFields = formAction.$$FORM_ACTION(prefix);
formAction = customFields.action || '';
formEncType = customFields.encType;
formMethod = customFields.method;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -897,4 +897,77 @@ describe('ReactFlightDOMForm', () => {

expect(form.action).toBe('http://localhost/permalink');
});

// @gate enableFormActions
// @gate enableAsyncActions
it('useFormState can return JSX state during MPA form submission', async () => {
const serverAction = serverExports(
async function action(prevState, formData) {
return <div>error message</div>;
},
);

function Form({action}) {
const [errorMsg, dispatch] = useFormState(action, null);
return <form action={dispatch}>{errorMsg}</form>;
}

const FormRef = await clientExports(Form);

const rscStream = ReactServerDOMServer.renderToReadableStream(
<FormRef action={serverAction} />,
webpackMap,
);
const response = ReactServerDOMClient.createFromReadableStream(rscStream, {
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
});
const ssrStream = await ReactDOMServer.renderToReadableStream(response);
await readIntoContainer(ssrStream);

const form1 = container.getElementsByTagName('form')[0];
expect(form1.textContent).toBe('');

async function submitTheForm() {
const form = container.getElementsByTagName('form')[0];
const {formState} = await submit(form);

// Simulate an MPA form submission by resetting the container and
// rendering again.
container.innerHTML = '';

const postbackRscStream = ReactServerDOMServer.renderToReadableStream(
<FormRef action={serverAction} />,
webpackMap,
);
const postbackResponse = ReactServerDOMClient.createFromReadableStream(
postbackRscStream,
{
ssrManifest: {
moduleMap: null,
moduleLoading: null,
},
},
);
const postbackSsrStream = await ReactDOMServer.renderToReadableStream(
postbackResponse,
{formState: formState},
);
await readIntoContainer(postbackSsrStream);
}

await expect(submitTheForm).toErrorDev(
'Warning: Failed to serialize an action for progressive enhancement:\n' +
'Error: React Element cannot be passed to Server Functions from the Client without a temporary reference set. Pass a TemporaryReferenceSet to the options.\n' +
' [<div/>]\n' +
' ^^^^^^',
);

// The error message was returned as JSX.
const form2 = container.getElementsByTagName('form')[0];
expect(form2.textContent).toBe('error message');
expect(form2.firstChild.tagName).toBe('DIV');
});
});