I am trying to get the submitted form data from a react-router-dom Form.
Below is my route (snippet from index.tsx):
import { ActionQuickConnect } from "./actions/ActionQuickConnect"
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{
path: "quick-connect",
element: <QuickConnect />,
action: ActionQuickConnect
}
],
},
]);
Here’s my ActionQuickConnect:
export const ActionQuickConnect = async ({ request }) => {
try {
const data = await request.formData();
console.log(data.getData('username'))
//!! This output: data.getData is not a function
} catch (e) {
console.log(e.message);
}
}
Component:
import { Form } from 'react-router-dom';
import React from "react";
export const QuickConnect:React.FC = () => {
<Form className="space-y-6" method="post" action="/quick-connect">
<input id="username" name="username" type="text"/>
</Form
}
Can someone see what the problem might be?
createBrowserRouter should be a part of data api (as far as I can see)
2
Answers
The issue you’re encountering in your React application with
react-router-dom
is related to how you’re trying to access form data in yourActionQuickConnect
function. TheformData()
function returns aFormData
object, butgetData
is not a method of theFormData
interface. Instead, you should use theget
method to retrieve the value of a specific form field.Here’s how you can modify your
ActionQuickConnect
function:In this corrected version,
data.get('username')
is used to retrieve the value associated with the ‘username’ field from the form data. Theget
method is the correct way to access values in aFormData
object.Additionally, ensure that your form component is correctly structured and closed. In your
QuickConnect
component, the<Form>
tag is not properly closed. Here’s the corrected version:Make sure to include the
return
statement and properly close the<Form>
tag. This will ensure that your form is rendered correctly and can submit data as expected.Well, most likely is that there is no function .getData() in data variable.
Do this and see what you get: