Christian Christian - 5 months ago 14
Javascript Question

Adding functions to redux store within reducer is an anti pattern?

say I have a component connected to the redux store. Within this store, there's a list of objects. For instance something like this:

ReduxStore: {
dataList: [
{name:'bla'},
{name:'blub'},
]
}


Is it actually an anti pattern to create and add a filter function within the reducer to create something like this:

ReduxStore: {
dataList: {
data:[
{name:'bla'},
{name:'blub'}
],
isNameAvailable: (name) => {/* search for name */}
}
}


It works great, but I'm not sure whether this was the intended way to go.

Answer

It's an anti-pattern because your store only cares about data, not computation. Once you start adding functions to your store, you lose the ability to serialize the data inside it.

However, it's pretty trivial to pull these kinds of helper functions out and turn them into standalone utility selectors which you can use to achieve the same thing.

function isNameAvailable(store, name) {
  /* search for `name` in `store` */
}

Now the function works independently of the store and you can keep them separate for testing.

From here, you can take a look at Reselect which allows you to turn your isNameAvailable function into a cached selector, meaning you'll only need to re-calculate as and when the appropriate data in the store is changed.