user6761897
user6761897

Reputation:

Copying objects in React-Redux reducers

I'm rank new to React and even newer to Redux thus the question.

So I have an initial state in my reducer which is Object = {}

Now I want to modify this state and return it with an object user.

So I'm expecting a result Object = {user}

User in itself has the following properties,

{A: 1, B:2, C:3}

If I use Object.assign({}, state, user} I get the following,

Object = {A: 1, B:2, C:3}

So how do I copy the user object to the state object as a parameter without splitting it up. Also how do I do this in case the object I'm adding is an array.

Upvotes: 2

Views: 2965

Answers (2)

Pineda
Pineda

Reputation: 7593

Try this:

Object.assign({}, state, { user: user })

Reason:

The objects you are passing in will overwrite the previous options, by passing in user, you are overwriting the current state with {A: 1, B:2, C:3} rather than overwriting the property in the object with the keyid user.


Alternatively (and if your setup supports it), you can use spread syntax as follows:

{
  ...state,
  user: user
}

actually, even shorter,

{
  ...state,
  user 
}

Object.assign is overkill for Redux.

Upvotes: 1

Eric Palakovich Carr
Eric Palakovich Carr

Reputation: 23308

Try this instead: Object.assign({}, state, {user})

EDIT: Responding to your comment below, if user was an array, say users, it would work the same:

> var state = {A: 1, B:2, C:3}
> var users = [1,2,3];
> Object.assign({}, state, {users});
{A: 1, B: 2, C: 3, users: [ 1, 2, 3 ] }

Upvotes: 2

Related Questions