-
I'm wondering what are the best practices around sending raw JSON to actions - I know Remix is very form-focused but sometimes forms just don't cut it and it feels like somewhat of a regression to handle things through hidden inputs. Right now I'm combining a hook to send JSON to the current route: export function useJsonSubmit(method: FormMethod = "post") {
const submit = useSubmit();
const route = useCurrentRoute();
return (data: Object) =>
submit({ body: JSON.stringify(data) }, { method: "post", action: route });
} with a server-side require function to get it: export async function requireJsonBody(request: Request) {
const form = await request.formData();
const rawBody = form.get("body");
if (!rawBody) {
throw json("Missing body", { status: 400 });
}
if (typeof rawBody !== "string") {
throw json("Malformed JSON body: expected string body", { status: 400 });
}
try {
return JSON.parse(rawBody);
} catch {
throw json("Malformed JSON body: could not parse", { status: 400 });
}
} but I can't help but feel that this is unnecessarily hacky as well, especially since it requires knowledge of that arbitrary Any tips on how to improve this? Thanks a lot in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 7 replies
-
There are multiple approach, a simple one would be to have a hidden input with the value being Another approach is to name your inputs like |
Beta Was this translation helpful? Give feedback.
There are multiple approach, a simple one would be to have a hidden input with the value being
JSON.stringify(object)
and then in your action doJSON.parse(formData.get("that input name"))
Another approach is to name your inputs like
object["key"]
, then useawait request.text()
to get a string of the whole request body and use a library likeqs
to parse the string (which is gonna a search param string) to an object and that lib can parse your input names to objects so your input with the example key would be like{ object: { key: "the value" } ]
, you could even use arrays this way.