Home > Mobile >  How to hook the change on property of array of objects?
How to hook the change on property of array of objects?

Time:10-15

I want to show the change of property in array of user objects. I use useEffect but it could not hook the change of property (or I missed something?).

an array of user objects.

// list of user
const [user, setUser] = React.useState = ([
  {
    name: 'Tom',
    age: 23
  },
  {
    name: 'Marry',
    age: 24
  },
  {
    name: 'Dan',
    age: 22
  },
  {
    name: 'Rose',
    age: 22
  },
  {
    name: 'Alice',
    age: 23
  }
])

I hook the change of user

React.useEffect(() => {
  console.log('useEffect: hook user')
  console.log(user)
}, [user])

Then, I update property age of the object index 1 after clicked the button by function handleUpdate().

function handleUpdate() {
  let v = user
  v[1].age = 99
  setUser(() => {
    return v
  })
  console.log('updated')
  console.log(user) 
}

Log show that the array was updated successfully, but log in useEffect not show anychange. log after updated array

CodePudding user response:

Please , read this article first - https://www.benmvp.com/blog/object-array-dependencies-react-useEffect-hook/ I am just used spread operator to return new array :

import "./styles.css";
import React from "react";

export default function App() {
  const [user, setUser] = React.useState([
    {
      name: "Tom",
      age: 23
    },
    {
      name: "Marry",
      age: 24
    },
    {
      name: "Dan",
      age: 22
    },
    {
      name: "Rose",
      age: 22
    },
    {
      name: "Alice",
      age: 23
    }
  ]);

  React.useEffect(() => {
    console.log("useEffect: hook user");
    console.log(user);
  }, [user]);

  const handleUpdate = () => {
    let v = [...user];
    console.log(user);
    v[1].age = 99;
    setUser(() => {
      return v;
    });
    console.log("updated");
    console.log(user);
  };

  return (
    <div onClick={handleUpdate} className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

https://codesandbox.io/s/solitary-brook-1wdqy?file=/src/App.js

CodePudding user response:

You just need to update your handleUpdate func like this:

  const handleUpdate = () => {
    let v = [...user];
    console.log("user: ", user);
    v[1].age = 99;
    console.warn("v: ", v)
    setUser(oldArray => [...oldArray, v]);
    console.log("updated user: ", user);
  };

Hope this works for you

  • Related