Search code examples
ngrxstate-managementngrx-store

Multi reference notes in NGRX


I have an app that holds people and notes about them. The notes are such that they could relate to many people (e.g. Note1 will appear for Person1 and Person 3).

I am using NGRX to hold my state in memory.

Now looking at the ngrx example app you can get a good example of a collection of books. There they use a state that holds an array of objects indexed by the bookId (for fast retrieval).

How would one do that when the items in the collection (in my case the notes) could relate to many people?

I started out by indexing the array of objects with the uid of the person:

export interface NoteCollection {
    [uid: string]: Note[];
}

To consider:

  • over time there will be many notes, so that state data can be rather large
  • creating a note object for each referenced person seem then a rather bad idea (data redundancy)
  • notes will be added/ edited/ deleted often, so there is a need for up-to-date data
  • there will be an offline db involved in the future
  • storing the entire notes in state will need some .filter() function for each person page accessed. With the state growing this could become slow:
 export const getPersonNotes: any = createSelector(getNotes, 
    getSelectedPerson, (notes: any, selectedPersonId: string) => {
      return notes.filter((note: Note) => note.refUid === selectedId);
    });

Alternative:

  • do not store the notes in state at all by making an api call each time you need notes related to person

Any suggestions? The alternative feels odd, because why use ngrx at all then when half the state is not in redux?


Solution

  • You could do something like this to remove the Note redundancy problem:

    interface NoteCollection {
        [noteId: string]: Note[];
    }
    
    interface PersonCollection {
        [personId: string]: Person;
    }
    
    interface Person {
        noteIds: string[];  // an array of noteIds. 
    }