• hold several entities
• entities unique/identi
fi
able
• can have an order
• can be implemented by various data structures
Collections
Slide 3
Slide 3 text
• add an entity, add many, ...
• update an entity, update many, ...
• remove entity, remove many, ...
• read speci
fi
c entity,
fi
nd entities matching a condition, ...
Operations on Collections
Slide 4
Slide 4 text
Immutable updates on arrays
Slide 5
Slide 5 text
// collection
let collection: Entity[] = [...];
// item we want to add
const newItem: Entity = { id: 'itemId', ... };
// simply appending to the end
collection = collection.concat(newItem);
collection = [...collection, newItem];
// beware of duplicates + order
Adding to the collection (array)
Slide 6
Slide 6 text
// collection
let collection: Entity[] = [...];
// id we want to remove
const removeId = 'itemId';
// filter the collection
collection = collection.filter(item => item.id !== removeId);
Removing from the collection (array)
Slide 7
Slide 7 text
// collection
let collection: Entity[] = [...];
// item we want to update
const updateId = 'itemId';
const update: Partial = { foobar: 42 };
// map the collection
collection = collection
.map(item => item.id === updateId ? { ...item, ...update } : item);
Updating an item in the collection (array)
Slide 8
Slide 8 text
// collection
let collection: Entity[] = [...];
// id we are trying to find
const target = 'itemId';
// find in the collection
const item: Entity | undefined = collection.find(item => item.id === target);
// worst case: iterates whole list without a match
Read an item from the collection (array) by id
Slide 9
Slide 9 text
// collection
let collection: Entity[] = [...];
// filter the collection
const items = collection.filter(item => item.foobar >= 42);
Find items in the collection (array) by condition
Slide 10
Slide 10 text
• many applications handle one or many collections of entities
• always same/similar CRUD code
• often similar logic in regards sorting + uniqueness of items
→ Abstraction possible!
→ @ngrx/entity provides the EntityAdapter
Boilerplate? Repetition?
Slide 11
Slide 11 text
Introducing the EntityAdapter
Slide 12
Slide 12 text
• stateless class provided by the @ngrx/entity package
• stores many entities ef
fi
ciently
• provides methods and selectors to manage a collection immutably
• agnostic, can be used in many contexts (Store, ComponentStore)
→ reduces boilerplate / repetition
→ keeps reducers small
What is the EntityAdapter?
let collection = entityAdapter.getInitialState();
// optionally initialise additional state properties
let collection = createEntityAdapter({
loading: false,
});
Get the initial collection state