wwilsman / redux-deep-diff

Higher order reducer to deep diff redux states
MIT License
23 stars 4 forks source link

Support arrays of objects as state #9

Open reZach opened 4 years ago

reZach commented 4 years ago

Can this library support arrays as a state? ie.

[
    {
        name: "A",
        height: 4,
        data: {
            // ...
        }
    },
    {
        name: "B",
        height: 8
        data: {
            // ...
        }
    },
]

You mention in the docs that

the deep-diff library calculates structural changes between two javascript objects. As such, your state must be a diffable object.

Instead of just diffing each side, could you iterate over all elements in an array and store the diffs of that?

I found your repo looking at this list, and realized that I'm essentially building your library here and figured it doesn't hurt to ask :smile:.

wwilsman commented 4 years ago

Hey @reZach! Thanks for the question!

Unfortunately, this library wasn't written with arrays in mind as the top-level state.

I'm definitely open to any PRs though! Potentially the easiest way would be to save this returned reducer as a reference, then in it's place do something like:

let historyReducer = (rawState, action) => {
  // ... original reducer contents here
}

return (rawState, action) => {
  if (Array.isArray(rawState)) {
    return rawState.map(item => historyReducer(item, action))
  } else {
    return historyReducer(rawState, action)
  }
}

I don't have much time lately to make these changes myself and add the proper tests. Another potential solution without modifying this library would be to key your state in a POJO or move the reducer one level higher and use the prefilter option to only produce diffs for your array.