I’m trying to update an existing array in react using useState, a react hook. What I’m doing in the function below is trying to update the array by id. I want to update the inner ‘inspections’ array and add a new inspection. But whats happening instead is that it’s adding to the end of the ‘data’ array and not to the end of ‘inspections’ array.
Here is my array:
export const data = [
{
id: Math.floor(Math.random() * 999999),
description: "",
type: "car",
inspections: [
{
id: Math.floor(Math.random() * 999999),
name: `Inspection${Math.floor(Math.random() * 999999)}`,
type: "any",
},
],
},
];
Here is my update function:
const [dataArray, setDataArray] = useState(data);
const [inspection, setInspection] = useState("");
function handleInspection(id) {
setDataArray((prevState) => [
...prevState,
{
id: id,
description: "",
type: "",
inspections: [
{
id: Math.floor(Math.random() * 999999),
name: `Inspection${Math.floor(Math.random() * 999999)}`,
type: inspection,
},
],
},
]);
}
Here is the data mapped and radio buttons, I’m using radio buttons to select what kind of inspection you can choose: any, car, lorry, van. Once you select an Inspection you should be able to click the button and ‘add a new inspection’ to an existing array of inspections.
{dataArray.map((vehicles) => {
return (
<div>
<div key={vehicles.id}>vehicle type:{vehicles.type}</div>
<ul>
{vehicles.inspections.map((inspection) => {
return <li>type: {inspection.type}</li>;
})}
lorry
<input
name="option"
type="radio"
className="form-control"
autoFocus={true}
onChange={() => setInspection("Lorry")}
aria-label="Enter the title of your todo"
placeholder="Enter a new todo"
value={inspection}
/>
van
<input
name="option"
type="radio"
className="form-control"
onChange={() => setInspection("Van")}
autoFocus={true}
aria-label="Enter the title of your todo"
placeholder="Enter a new todo"
value={inspection}
/>
car
<input
name="option"
type="radio"
className="form-control"
onChange={() => setInspection("Car")}
autoFocus={true}
aria-label="Enter the title of your todo"
placeholder="Enter a new todo"
value={inspection}
/>
any
<input
name="option"
type="radio"
className="form-control"
onChange={() => setInspection("Any")}
autoFocus={true}
aria-label="Enter the title of your todo"
placeholder="Enter a new todo"
value={inspection}
/>
</ul>
<button
className="addButton"
onClick={() => handleInspection(vehicles.id)}
>
Add Inspection
</button>
</div>
);
})}