I have a state variable which is an empty array
const [boxes, setBoxes] = useState([]);
const [showAddGalley,setShowAddGalley]=useState({galleyNo:""});
I have a function which takes input from a form and on each time i submit i need to set the boxes array with object from the form,
my submit function is
const onSubmitGalleyBoxes=(e,updated)=>{
if(updated){
setBoxes((prev)=>{return {...prev,`${showAddGalley.galleyNo}`:{updated}}})
}
}
my intention is got get the boxes array on each submit like the below
const boxes=[{id: "Galley10", galleyNo: "440S", galleyItem: "Veg Meals"},
{id: "Galley11", galleyNo: "340S", galleyItem: "Non Veg Meals"}
]
my updated object in the function in onSubmitGalleyBoxes is,
const updated={galleyNo: "340S", galleyItem: "Non Veg Meals"}
the setBoxes i am doing in the onSubmitGalleyBoxes doesn’t seems to work what is wrong here
2
Answers
This will correctly update your boxes state variable:
if you just want to push data into the array
or if you want to update data inside value:
You have a function that – on form submission – takes the object generated by the form and updates the
boxes
array with that object.The correct syntax for this would be
setBoxes(prev => [...prev, object]);
.Here’s a small working example that uses a
GalleyForm
component (which maintains its own state), and displays theboxes
state whenever it’s updated with a new form object.