Using the data router in React-Router 6 I want to redirect the user from an action, but also I need to return data. Can you do both at the same time?
Redirect works, but no way to send data.
export async function routerAction() {
return redirect("/some-url");
}
Should work, but does not.
export async function routerAction() {
return new Response(JSON.stringify({ foo: "bar" }), {
status: 302,
headers: {
"Content-Type": "application/json; utf-8",
Location: "/some-url",
},
});
}
In my component I try to retrieve the data like this:
function SomeComponent() {
let actionData = useActionData(); // unfortunately, actionData is undefined
}
2
Answers
Seems like you have to find different way to pass data into other component.
useActionData()
only returns the data when you use<Form method="post">
oruseSubmit()
Based on this answer it would seem that modern browsers simply ignore the message body of 302 responses.
What I can suggest then is to just return a JSON response which includes the data and redirect target back to the component submitting the action, then use a
useEffect
hook to effect an imperative redirect to the target route with the data payload.Example:
Instead of using the
useActionData
hook use theuseLocation
hook to access the passed route state.Demo