2

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.

1
  • Not sure what you mean by splitting it up - can you add the object that you would like the store to be? Commented Nov 28, 2016 at 21:06

2 Answers 2

2

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 ] }
Sign up to request clarification or add additional context in comments.

3 Comments

hehe, just beat me to it!
Now how can I do this, when the object I'm adding is an array?
@StochasticNerd you can have a look at the this answer stackoverflow.com/questions/40040102/…
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.