Skip to content
Advertisement

useState not working with Array of Objects

So I am working with React Hooks and with an array of names which will have buttons. On clicking those buttons the corresponding name would disappear. But the array is not updating at all.

import React, {useState} from "react";
import Profile from "./profile.js";
import './App.css';


const data = [
  {name: "A"},
  {name: "B"},
  {name: "C"},
  {name: "D"},
]
function App() {

  const [people, setPeople] = useState(data);

  return (
    <div className="App">
      <h1>Birthdays Today</h1> 
      {
        data.map((person)=>{
          const name = person.name;
          return(
            <div>
              <Profile name={name}/>
              <button type="button" className="btn" onClick={()=>{
                let newPeople = people.filter(person => person.name!=={name});
                console.log(newPeople);
                setPeople(newPeople);
              }}>Clear this birthday</button>
            </div>
          )
        })
      }
      <button type="button" className="btn" onClick={()=>setPeople([])}>Clear all birthdays</button>
    </div>
  );
}

export default App;

Please advise what can be done, I’m a newbie in React. Thank you!

Advertisement

Answer

You are using your data variable which never changes instead of using the “people” variable which is your “react state”.

Just use “people” in your render.

May I advise you to have a look here : https://reactjs.org/docs/hooks-reference.html#usestate You will find several examples

{
        person.map((person)=>{
          const name = person.name;
          return(
            <div>
              <Profile name={name}/>
              <button type="button" className="btn" onClick={()=>{
                let newPeople = people.filter(person => person.name!=={name});
                console.log(newPeople);
                setPeople(newPeople);
              }}>Clear this birthday</button>
            </div>
          )
        })
      }
Advertisement