0

How can I push array in objectlist in react state in loop?

My default state:

this.state = {
            users: [
                {
                    id:1,
                    name: 'John'
                },
                {
                    id:2,
                    name: 'Nick'
                }
            ]
        };

I tried something like this, but it's not working

changeHandler (currentUser, newValue) {
        const users = this.state.users;
        for (var i in users) {
            if (users[i].id == currentUser) {
                this.setState({
                    users: [...this.state.users[i], {newValue: newValue}]
                })
            }
            break;
        }
    }

So I expect to see:

default state - {id:1,name: 'John'},{id:2, name: 'Nick'} 
use changeHandler(2,1) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1]}
use changeHandler(2,2) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1,2]}
use changeHandler(2,3) - {id:1,name: 'John'},{id:2, name: 'Nick', newValue: [1,2,3]}

3 Answers 3

1

You can map and update the state using spread syntax like

changeHandler (currentUser, newValue) {
    const users = this.state.users;
    this.setState(prevState => ({
       users: prevState.users.map((user => {
           if (user.id == currentUser) {
              return {
                  ...user,
                  newValue: [...(user.newValue || []), newValue]
              }
           }
           return user
       }))
    }))
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use map:

this.state.users.map(
  (user)=>user.id===currentUser
    //if user id is current user then copy user to new object {...user}
    //set newValue to user.newValue or empty array newValue:(user.newValue||[])
    //add the newValue to user.newValue: .concat(newValue)
    ? {...user,newValue:(user.newValue||[]).concat(newValue)
    //user is is not currentUser, just return the user as is
    : user
)

2 Comments

In React, state is should stay immutable, you have to use setState method to update it.
@mab yes, the complete version is: this.setState({...this.state,users:this.state.users.map(---
0

Short one:

changeHandler (currentUserId, newValue) {
  this.setState(({ users }) => ({
    users: users.map(user => ({
      ...user,
      ...(
        user.id === currentUserId
          ? { newValue: [...(user.newValue || []), newValue]}
          : {}
      ),
    }))
  }));
}

Long one:

changeHandler (currentUserId, newValue) {
  this.setState(({ users }) => {
    const otherUsers = users.filter({ id } => id !== currentUserId);
    const currentUser = users.find({ id } => id === currentUserId);
    return {
      users: [
        ...otherUsers,
        {
          ...currentUser,
          newValue: [
            ...(currentUser.newValue || []),
            newValue
          ],
        },
      ],
    };
  });
}

Short version of long one:

changeHandler (currentUserId, newValue) {
  this.setState(({ users }) => ({
    users: [
      ...users.filter({ id } => id !== currentUserId),
      {
        ...users.find({ id } => id === currentUserId),
        newValue: [...(currentUser.newValue || []), newValue],
      },
    ],
  }));
}

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.