Skip to content

Instantly share code, notes, and snippets.

@TyrealGray
Last active January 15, 2018 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TyrealGray/8632b22d08735ad1ff78595b89ef9e1a to your computer and use it in GitHub Desktop.
Save TyrealGray/8632b22d08735ad1ff78595b89ef9e1a to your computer and use it in GitHub Desktop.

To update an array in Redux store

Because the principle of the Redux state, the state always is read-only. And if we want to update some variable, we always have to return a new value. The problem is javascript always pass object by reference, and redux store could not recognize Array element 's data changes because Array reference is not changed. The right way to update

For example, let's assume we have an array in our state name "events" and contains many event objects.

E.g. the right way to update:

function updateEvnet(state, ID, data ) {
  let events = [...state.events];
  for (let index = 0; index < events.length; ++index) {
     let eventData = events[index];
     if (eventData.ID !== ID) {
        continue;
     }
     const event = {
        ...eventData,
        data
     };
     events[index] = event;
     break;
  }
  return {
     ...state,
     events : events
  }
}

Using spread syntax(es6) could easily make copy of a variable, see here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

let events = [...state.events] is equal to: 
let events = [];
for(let index =0; index < state.events.length; ++index){
	events.push( state.events[index] );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment