skip to Main Content
const [user, setUser] = useState({firstName: "AA",lastName: "BB",address: [{name: "AA",count: 0}]});
const plus = () => {setUser([ ...user.address, user.address[0].count + 1 ]);}
return (
<h1>{user.address[0].count}
)

I tried to wrap up setUser to object

2

Answers


  1. Spread the object and inner array separately when updating the state:

    setUser({ ...user, address : [ {...user.address[0], count : user.address[0].count + 1}, 
                                  ...user.address.slice(1) ] });
    
    Login or Signup to reply.
  2. In your code, you are not properly updating the state. If spread operations are confusing for you, you can use immer.

    Install immer using one of the following.

    npm i immer
    pnpm add immer
    yarn add immer
    

    Then you can use immer as follows.

    import produce from "immer";
    
    ...
    ...
    
    setUser(produce(state => {
      user.address[0].count += 1; 
    }));
    
    ...
    ...
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search