I am trying to use useState in my react functional component to update array of objects but nothing is happening. Here is the code I am trying:
const countriesData = [
{ id: 1, name: "India", person: "Harpreet" },
{ id: 2, name: "Aus", person: "Monty" },
{ id: 3, name: "UK", person: "Preet" },
];
ReactDom.render(<App />, document.getElementById("root"));
function App() {
const [name, setName] = useState(countriesData);
const arr = [{ id: name.length + 1, name: "Pak", person: "Mnm" }];
const AddMe = () => {
setName({ ...name, ...arr });
};
return (
<>
<CountryName data={countriesData} />
<button onClick={AddMe}> Add me</button>
</>
);
}
function CountryName({ data }) {
return (
<React.Fragment>
{data.map((element, index) => (
<div key={index}>
<h1>{element.person}</h1>
<span>from : {element.name}</span>
</div>
))}
</React.Fragment>
);
}
I am a newbie in React. I also tried having prevState as setName argument and then add like setName(prevState{ ...pevState, ...arr }); Already had a look on so many sources but no luck. Any help will be appreciated. Thanks!
nameis an array. InAddMeyou are trying to merge objects