Search code examples
javascriptreactjsreduxside-effectsmutation

JavaScript: Will a = Object.assign({}, a, {k: v}) mutate a?


I have a object stored as key, value pairs in a url as query params. The keys of that object may change, and I want to use each of the key, value pairs in that object to update the key, value pairs of a state object in a redux app. I need to do so in a way that doesn't mutate the state object, and am currently attempting to achieve this goal as follows:

case 'LOAD_SEARCH_FROM_URL':
  let _state = Object.assign({}, state);
  const args = action.obj.substring(1).split('&');
  args.map((arg) => {
    const split = arg.split('=');
    _state = Object.assign({}, _state, {
      [split[0]]: JSON.parse( decodeURIComponent( split[1] ) )
    })
  })
  return _state;

This works fine in simple tests, but I wanted to make sure that this is not in fact performing any mutations. I'd be grateful for any insights others can offer on this question!


Solution

  • No, Object.assign will only mutate the target (the first argument), which in your case is a newly created empty object. The sources (all subsequent arguments) will not be modified.