An util tool to merge store data for flux architecture
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib
test
.gitignore
.jshintignore
.jshintrc
LICENSE
README.md
index.js
package.json

README.md

traction

Help flux store to merge new data trigger from action, for example: API, user interface, local storage... This tool will make your store management super easy by one line code: traction.merge(newData).to(array).basedOn('id');

Install

Install with npm

npm install --save traction

Examples

Merge object to array

Say we have an UsersStore, and we fetch one user from API:

var traction = require('traction');
var users = [{
    id: 1,
    name: 'a'
}];

var onFetchOneUserSuccess = function(newUser) {
    users = traction.merge(newUser).to(users).basedOn('id');
};

onFetchOneUserSuccess({
    id: 1,
    name: 'b'
});
onFetchOneUserSuccess({
    id: 2,
    name: 'c'
});
console.log(users);

The output should be:

[{
    id: 1,
    name: 'b'
}, {
    id: 2,
    name: 'c'
}]

Merge array to array

Say we have an UsersStore, and we fetch multiple users from API:

var traction = require('traction');
var users = [{
    id: 1,
    name: 'a'
}, {
    id: 2,
    name: 'b'
}];

var onFetchOneUserSuccess = function(newUsers) {
    users = traction.merge(newUsers).to(users).basedOn('id');
};

onFetchOneUserSuccess({
    id: 2,
    name: 'c'
}, {
    id: 3,
    name: 'd'
});
console.log(users);

The output should be:

[{
    id: 1,
    name: 'a'
}, {
    id: 2,
    name: 'c'
}, {
    id: 3,
    name: 'd'
}]

NOTICE: the merge is deeply merge.

Merge based on multiple keys

Say we have an UsersStore, and we fetch one user from API:

var traction = require('traction');
var users = [{
    name: 'a',
    gender: 'male',
    age: 11
}, {
   name: 'a',
   gender: 'female',
   age: 20
}];

var onFetchOneUserSuccess = function(newUser) {
    users = traction.merge(newUser).to(users).basedOn('name', 'gender');
};

onFetchOneUserSuccess({
    name: 'a',
    gender: 'female',
    age: 30
});

console.log(users);

The output should be:

[{
     name: 'a',
     gender: 'male',
     age: 11
}, {
    name: 'a',
    gender: 'female',
    age: 30
}]