Preet
Preet

Reputation: 25

React useState not updating array of objects

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!

Upvotes: 1

Views: 6257

Answers (2)

Shubham Verma
Shubham Verma

Reputation: 5054

You need to do:

setName([ ...name, ...arr ]);

or

setName((prev) => [...prev, ...arr]);

and also update data:

<CountryName data={name} />

Here is full code:

import React, { useState } from "react";
import "./styles.css";

const countriesData = [
  { id: 1, name: "India", person: "Harpreet" },
  { id: 2, name: "Aus", person: "Monty" },
  { id: 3, name: "UK", person: "Preet" }
];
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>
  );
}
export default function App() {
  const [name, setName] = useState(countriesData);

  const arr = [{ id: name.length + 1, name: "Pak", person: "Mnm" }];
  const AddMe = () => {
    setName((prev) => [...prev, ...arr]);
  };
  return (
    <>
      <CountryName data={name} />
      <button onClick={AddMe}> Add me</button>
    </>
  );
}


Here is the demo: https://codesandbox.io/s/keen-buck-ue9sn?file=/src/App.js:0-826

Upvotes: 1

norbitrial
norbitrial

Reputation: 15166

The initial data is an array, see in countriesData variable, also in setName you try to use {}.

You should call with [] instead of {} as:

setName([ ...name, ...arr ]);

Upvotes: 4

Related Questions