I am trying to build a form in which you can dynamically add fields and subfields. As an example, my form looks like this:
Store information:
Name
Items inventory: [] (this is the nested array part,
you press a button and can add another item to the inventory)
***Buttons to add more items to this store***
***Buttons to add more stores***
The code I am using to achieve this looks like this. I have updated to reflect the answers that I got so far and also the proper syntax for (there was an issue with the closing tags)
function StoreForm() {
const [storeInputs, setStoreInputs] = useState([
{ storeName: "", items: [{ itemName: "" }] },
]);
///...
return (
{storeInputs.map((store,index) =>
{
//input data here
{store.items.map((item,i) =>
{
//This is where it throws the undefined error
//do something
}
)
}
}
)
)
}
The above code now works on the first run, but when I try to add another store to the form, it throws the undefined error again. Here is the code I am using for the buttons that add another store:
const handleRemoveStore = (index) => {
const list = [...storeInputs];
list.splice(index, 1);
setItemsInputs(list);
};
const handleAddStore = () => {
setItemsInputs([...storeInputs, { storeName: "", items: [{ itemName: "" }] }]);
};
Thank you for the answers thus far!
On
return (
{storeInputs.map(store,index) =>
{
//input data here
{storeInputs.items.map(item,i) =>
{
//This is where it throws the undefined error
//do something
}
}
}
)
You map two time on storeInputs, you need to do someting like :
return (
{storeInputs.map((input,index) =>
{
//input data here
{input.items.map((item,i) =>
{
//This is where it throws the undefined error
//do something
}
}
}
)
Be careful about the () around the params, you do :
x.map(a, index) => {})
In fact is :
x.map((a, index) => {})
The first ( is for the map methods, second is for the params of the function inside your map.
The storeInputs
state hasn't any items
property to map in the inner mapping. That property belongs to the store
object mapped from the outer loop.
function StoreForm() {
const [storeInputs, setStoreInputs] = useState([
{ storeName: "", items: [{ itemName: "" }] },
]);
...
return storeInputs.map((storeInput, index) => {
// input data here
return (
...
{storeInput.items.map((item, i) => { ... })}
...
);
});
}