#useActionData not working with responses

1 messages · Page 1 of 1 (latest)

safe path
#

Hello!

Does anyone know how to make type inference work when your action returns a Response? The typing breaks and I cannot access anything in the returned data unless I manually type the return value.

Example:

export async function action({ request }: ActionArgs) {
  const url = new URL(request.url);
  const token = url.searchParams.get('token');

  const result = await resetPasswordWithToken(await inputFromForm(request), {
    resetToken: token,
  });

  // If there was an error, we return that JSON back directly.
  if (!result.success) {
    return {
      formError: result.errors.map((error) => error.message).join('\n'),
    };
  }

  // Otherwise we set a flash message and redirect back to the sign in page.
  const session = await sessionStorage.getSession(
    request.headers.get('Cookie')
  );
  session.flash('statusMessage', {
    type: 'success',
    message: result.data.message,
  });

  return redirect('/sign-in', {
    headers: {
      'Set-Cookie': await sessionStorage.commitSession(session),
    },
  });
}

//...

const actionData = useActionData<typeof action>();

The type of actionData is as follows:

const actionData: SerializeObject<UndefinedToOptional<Response>> | SerializeObject<UndefinedToOptional<{ formError: string; }>> | undefined;
silver plume
#

You'll probably want to throw (instead of return) your redirects/errors so that those don't get considered when inferring the action data type.

Our serialization type utilities try to make a union of all the serialized types for each possible return in your action function, so having returns that don't return data you expect to want from useActionData can screw that up

safe path
#

However when I throw from a loader it works as expected.

silver plume
#

Ah that makes sense. So yea I think the issue is that the serialization type helpers assume you only ever return Responses with JSON data, so this is a bug. Could you file an issue on GitHub?

safe path
#

Actually, it looks like the thrown redirect is working, it just auto-imported from the wrong place! My bad, haha.