Does JSON.parse(JSON.stringify(state)) guarantee no mutation of redux state?

javascript, json, reactjs, redux, state

Solution

Yes this does a deep clone, regardless of how expensive it is. The difficulty (as hinted in comment under the question) is to make sure `state` stays untouched everywhere else.

Since you're asking for other approaches, and that would not fit in a comment, I suggest to take a look at ImmutableJS, which eliminates the issue of tracking state mutation bugs (but might come with its own limitations):

const { Map } = require('immutable')
const map1 = Map({ a: 1, b: 2, c: 3 })
const map2 = map1.set('b', 50)
map1.get('b') // 2
map2.get('b') // 50

Problem

I've been tracking down an issue where a redux store correctly updates, but the component does not reflect the change. I've tried multiple ways of making sure I'm not mutating the state, however the issue persists. My reducers commonly take the form: ``` case 'ADD_OBJECT_TO_OBJECT_OF_OBJECTS': { newState = copyState(state); newState.objectOfObjects[action.id] = action.obj; return newState; } ``` For my copyState function, I usually use nested Object.assign() calls, but avoiding errors isn't so straightforward. For testing, to make sure I'm not mutating state, is it correct to use ``` const copyState = (state) => { return JSON.parse(JSON.stringify(state)); }; ``` as a guaranteed method of not mutating (redux) state, regardless of how expensive the process is? If not, are there any other deep copy methods that I can rely on for ensuring I'm not mutating state? EDIT: Considering that other people might be having the same issue, I'll relay the solution to the problem I was having. I was trying to dispatch an action, and then in the line after, I was trying to access data from the store that was updated in the previous line. ``` dispatchAction(data) // let's say this updates a part of the redux state called 'collection' console.log(this.props.collection) // This will not be updated! ``` Refer to https://github.com/reactjs/redux/issues/1543

Original source