In Remix, how do you return json
first and then redirect
after a success call on the API?
export const action: ActionFunction = async ({
request,
}: ActionFunctionArgs) => {
const formData = await request.formData();
try {
const { project } = await sampleAPICall(formData);
return json({
title: "Success",
message: "Yehey!",
});
throw redirect(`/${project?.id}`);
} catch (error) {
return json({
variant: "destructive",
message: "Oh no....",
});
}
};
2
Answers
I think you need to structure your code to handle the redirection separately from the JSON response. You cannot have code that executes after a return statement.
Hopefully I was able to help! Best of luck! 🙂
Redirects can’t have a body, so you can’t include a JSON payload in a redirect. If you want to display a message on the redirected route, you would typically use session flash.
https://remix.run/docs/en/main/utils/sessions#sessionflashkey-value
Then in your project route, you can display the message from flash