0

I have a redux reducer as follows:

function x(state = null, action){
   switch(action){
      case 'FILTER_DATA': {
        let { data } = state;
        let newData = someOperation(data);
        let s1 = deepCopy(newData);
        let s2 = s1.filter((v,i) => i%2);
        return {
          ...state,
          v1: s1,
          v2: s2
        };
     }
   }
}

If s1 is an array of nested objects - then some deep reference inside s2 will also point to the same object in memory.

Is it okay for a reducer to return a modified state - where 2 keys are almost pointing to the same object? Does it make the reducer impure and the overall code to function incorrectly??

Probosckie
  • 1,585
  • 4
  • 25
  • 40
  • 1
    If `someOperation` doesn't mutate the data then you're fine. Not sure why you would deep copy s1 though. The filter function will not mutate the original array so it seems unnecessary. – HMR Dec 12 '18 at 08:55

1 Answers1

0

You can add as many keys as you want, and it is very common for a reducer to modify the state.

It is better to do the 'someOperation' calculations before sending to action to make it cleaner. You don't need to create a copy as long you do not mutate, so you can delete deepCopy. Everything else is ok, as you concatenate correctly the object.

If you want to add multiple filters, you can add one reducer and action for each filter, and cross them with selectors: https://github.com/reduxjs/reselect.

PS: it's better to use const following best practices.

Psartek
  • 481
  • 3
  • 9