Rami Chasygov
Rami Chasygov

Reputation: 2784

Adding one element in array in React-Redux

I have a project, where I use react-redux, and I have a reducer, which by idea should add one element in array and return new array. How I can do this?

/*---- Reducer ----*/
case CHANGE_EVENT_USERS:
  return { ...state, users: payload };
 
/*---- Here's my hopeless tryings ----*/

userClickHandler() {
  const { id, homeFloor, avatarUrl, login } = this.props;
  const user = { id, homeFloor, avatarUrl, login };
  this.props.changeEventUsers([...user]); // []
  this.props.changeEventUsers(this.props.event.users.push()); // number
}

Upvotes: 2

Views: 1426

Answers (5)

Rami Chasygov
Rami Chasygov

Reputation: 2784

I found my solution:

this.props.changeEventUsers([...this.props.event.users, user]);

Upvotes: 0

SherylHohman
SherylHohman

Reputation: 17900

Use concat()

const initialArray = [1, 2, 3];  
const elemenToAdd = 4; 
const newArray= initialArray.concat([elementToAdd]);  

[1, 2, 3, 4]

Notice I'm using const here to emphasize that the initial array was not mutated.

The great thing about the method above, it's that it can be used to chain operations together.
result = initialArray.concat(..).filter(..).concat(..);
(where .. represents skipped code details)

You can also use concat by passing in arrays as parameters:
newArray = concat(initialArray, [elementToadd])

Or use es7 spread operator syntax for array concatenating:
newArray = [...initialArray, elementToAdd, ...[5], [6] ];

[1, 2, 3, 4, 5, [6] ]

Use ... to send individual elements of the supplied array to be elements in the new array; without the dots, the supplied array is itself the element.

So in the your case, the line in question could be written as:

Upvotes: 1

jb cazaux
jb cazaux

Reputation: 320

I like better the syntax of concat. In your reducer do:

case CHANGE_EVENT_USERS:
  return users.concat(action.payload);

Upvotes: 2

Matus
Matus

Reputation: 100

I'm not sure if I understand you correctly but from my understanding the solution to your problem would look something like this:

case CHANGE_EVENT_USERS:
  return { ...state, users: [ ...state.users, action.payload ] };

Upvotes: 3

Raul Rene
Raul Rene

Reputation: 10270

Do the add directly in the reducer.

From your component

this.props.changeEventUsers(newUser); // add the new user

In the reducer

return { ...state, users: [...state.users, payload] }; 

I made the assumption that "payload" contains the info coming from the action and the users array is by default initialised with an empty array value []

Upvotes: 1

Related Questions