I would like to ask question. I have vanilla React app, using createBrowserRouter from react-router-dom. I would like to use action to send data to a server. I have a form component where I have want to get all informations.So I am using input with names so I can use the in action function via formData. But I ran into a problem. Inside of my FormComponent I have a state called items. In my Form I have a div where I map over items to create div with 3 inputs. One for name,quantity and price. So far ok, I keep track of all the changes, but then when I want to submit my local items, I dont know how.
const FormComponent = () =>
const [items, setItems] = useState<Item[]>([
{ name: '', quantity: 1, price: 0 },
])
const handleItemChange = (
index: number,
field: keyof Item,
value: Item[keyof Item]
) => {
const newItems: any[] = [...items];
// assign the new value
newItems[index][field] = value;
setItems(newItems);
};
const addItem = () => {
setItems([...items, { name: '', quantity: 1, price: 0 }]);
};
return (
<Form method="post">
.....
<div>
<h3>Items</h3>
{items.map((item, index) => (
<div key={index}>
<label>
Name:
<input
type='text'
value={item.name}
onChange={(e) =>
handleItemChange(index, 'name', e.target.value)
}
required
/>
</label>
<label>
Quantity:
<input
type='number'
value={item.quantity}
onChange={(e) =>
handleItemChange(index, 'quantity', Number(e.target.value))
}
required
/>
</label>
<label>
Price:
<input
type='number'
value={item.price}
onChange={(e) =>
handleItemChange(index, 'price', Number(e.target.value))
}
required
/>
</label>
</div>
))}
<button type='button' onClick={addItem}>
Add Item
</button>
</div>
....
</Form>
)
}
So my question is, how can I pass data from my localstate to the action ? Thank you in advance
I tried already using the onSubmit way on my form, but then I dont see the data in action.
I have Login and Register page, where everything works, but they are simple components so it was easy to implement the action.
I´ve been lost for a while now.
Lubos Jurca is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.