I have a list of elements in a react js application.
import "./styles.css";
import React from 'react';
const carsData = [
{name: "first car", id: 1, meta: [{id:1, title:'first meta'}]},
{name: "second car", id: 2, meta: [{id:2, title:'second meta'}]},
{name: "third car", id: 3, meta: [{id:4, title:'last meta'}]},
]
export default function App({cars = carsData}) {
const [carsState, setCarsState] = React.useState(cars)
const newItem = {name: "first car", id: 1, meta: [{id:10, title:'added meta'}]}
const click = () => {
setCarsState([...carsState, newItem])
}
return (
<div className="App">
<button onClick={click}>click</button>
{
carsState.map(c => {
return <p key={c.name}>{c.name} - meta:
{c.meta.map((m, k) => <span key={k}>{m.title}</span>)}</p>
})
}
</div>
);
}
If the user clicks on the button, it should change the first item from the array. Now if i click on the button, the new item is added at the end of the list, but it should change the first item, because the id is the same.
Why the code doe not work and how to change to get the expected result?
demo: https://codesandbox.io/s/ecstatic-sound-rkgbe?file=/src/App.tsx:56-64