1

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!

2
  • name is an array. In AddMe you are trying to merge objects Commented Aug 31, 2020 at 12:43
  • You are changing state property name, but you are always looping over countries data. Did you intend to loop over property name? Commented Aug 31, 2020 at 12:49

2 Answers 2

4

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 ]);
Sign up to request clarification or add additional context in comments.

3 Comments

Tried this but this is also not working. Nothing is happening in browser. No error
Probably you should use <CountryName data={name} /> instead of <CountryName data={countriesData} />.
Shouldn't it update the DOM also? Seems like console.log is working with name but not changing in DOM
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.