NGRX operation duplicity

42 Views Asked by At

I have groups and words that belong to each group (1 - inf). When page is loaded I select all groups that I want to show. Each group has an array of word ids that it contains (following data normalization recommendations), so I select words using groupId like this:

export const selectWordsByGroupId = (groupId: string) => createSelector(
    selectWordEntities,
    selectGroupEntities,
    (wordEntities, groupEntities) => {
        let wordIds = groupEntities[groupId].wordIds;
        return wordIds.map(wordId => wordEntities[wordId])
    }
);

but then I also have a page for each individual group where I select data using params:

getCurrentGroupExerciseWords: createSelector(
    getParams,
    selectGroupEntities,
    selectWordEntities,
    (params, groupEntities, wordEntities) => {
        let wordIds = groupEntities[params.groupId].wordIds;
        return wordIds.map(wordId => wordEntities[wordId])
    }
),

The issue I have is that the operations are fundamentally the same - retrieve words using group ID. The operation was already performed but I have no way of leveraging memoization, so I get on second read 0(n) instead of 0(1).

I understand that my data scale and complexity are trivial, but this seems like a common problem and it feels dirty to have to perform same operation twice, even more so after going through all the troubles of setting up ngrx. I passed last several days agonizing over this stupid thing. Is there a solution or am I loosing my mind for no reason?

One great solution would be, if it was possible, to use selector inside projector function like so:

getCurrentGroupExerciseWords: createSelector(
    getParams,
    (params) => {
        return selectWordsByGroupId(params.groupId)
    }
),

But instead of data I would be getting a selector, not to mention that factory selectors supposedly don´t memoize!(at least second part I could fix with Lodash) P.S. Links to resources on how to approach structuring your data in ngrx would be much appreciated.

0

There are 0 best solutions below