Entity Adapter supports updating a collection with the "updateOne" method call. However, when the updated values' keys don't exist this leads to a specific entity not being updated. See code example.
However, internally the entity adapter uses Object.assign()
which while is nice isn't always what I want. I would like it to basically replace the entity in question.
Moreover, if the object in question has the structure A (see below). Then some arbitrary database operation occurred and returned the updated JSON back the frontend. The reducer would eventually get that information in the form.
const originalValue: MyClass = new MyClass('value 1', 'value 2');
const updatedValueFromServer: MyClass = new MyClass('updated');
Then internally to the entity adapter it looks like
const updateValue = Object.assign(originalValue, updatedValueFromServer);
// which would result in ...
// { key1: 'updated', key2: 'value 2' }
// while I would like
// { key1: 'updated' }
// Or
// { key1: 'updated', key2: null }
case ActionTypes.UPDATE_SUCCESS:
return collectionAdapter.updateOne({
changes: action.payload.alertSubscription,
id: action.payload.alertSubscription.uniqueID
}, {
...state,
isLoading: false,
error: null
});
export class MyClass {
constructor(public key1?: string, public key2?: string) { }
}
I would like it to simply replace the value in the collection, and not attempt to poorly update by internally calling "Object.assign()". Alternatively, somehow setting the keys in the object to null would be beneficial.
setOne is the way to go.
setOne(payload, state);
Here is full documentation.
addOne: Add one entity to the collection
addMany: Add multiple entities to the collection
setAll: Replace current collection with provided collection
setOne: Add or Replace one entity in the collection
removeOne: Remove one entity from the collection
removeMany: Remove multiple entities from the collection, by id or by predicate
removeAll: Clear entity collection
updateOne: Update one entity in the collection. Supports partial updates.
updateMany: Update multiple entities in the collection. Supports partial updates.
upsertOne: Add or Update one entity in the collection. Supports partial updates.
upsertMany: Add or Update multiple entities in the collection. Supports partial updates.
map: Update multiple entities in the collection by defining a map function, similar to Array.map
You will have to use the upsertOne
or upsertAll
method - see NgRx docs
upsertOne: Add or Update one entity in the collection
upsertMany: Add or Update multiple entities in the collection
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With