Add "append" to loadEntity
mikechabot opened this issue · 1 comments
Currently, loadEntity
overwrites the entity in the store on subsequent calls. This was by design and meant to be a simple implementation. But without added complexity, loadEntity
could accept an append
argument (boolean), which would optionally append new data from the call to the entity in the store.
loadEntity
now accepts an options
argument that can contain a property named append
; it defaults to false
, which matches the existing behavior of redux-entity
, which is, all calls to an implementation of loadEntity
(such as fetchFoo
below) overwrite whatever exists in the entity's data
property.
However if append
is true
, subsequent calls to fetchFoo
will combine the result of the promise with the existing data in the entity.
Objects
If the result of your data promise is an object
, redux-entity
creates an array, and pushes the object onto it - it will NOT merge objects.
For example, the promise below returns an object literal. With append
set to true and fetchFoo
invoked twice, we can see two randomNum
objects in the state's data
array:
function fetchFoo () {
return loadEntity(
'foobar',
Promise.resolve({ randomNum: Math.random() }),
{ append: true }
);
}
fetchFoo()(dispatch); // Call once
fetchFoo()(dispatch); // Call twice
Final state
{
"foobar":{
"isFetching":false,
"lastUpdated":1480807317751,
"data":[
{
"randomNum":0.99437688223453
},
{
"randomNum":0.02760231206535746
}
],
"error":null
}
}
Arrays
If your promise returns an array
, redux-entity
concatenates it with the existing data
on the entity.
For example, the promise below returns an array with two random numbers. With append
set to true and fetchFoo
invoked twice, we can see four (4) random numbers in the state's data
array:
// my custom entity
function fetchFoo () {
return loadEntity(
'foobar',
Promise.resolve([Math.random(), Math.random()]),
{ append: true }
);
}
fetchFoo()(dispatch); // Call once
fetchFoo()(dispatch); // Call twice
State
{
"foobar":{
"isFetching":false,
"lastUpdated":1480807969474,
"data":[
0.3740764599842803,
0.46176137669506945,
0.9866826383932925,
0.7325032000955436
],
"error":null
}
}