-
-
Save Tauka/0d664fd0a0eb224c20bb80ae720b8ab9 to your computer and use it in GitHub Desktop.
products-basket-selectors-example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// fake reselect | |
const createSelector = (deps, body) => (state, props) => | |
body(...deps.map(dep => dep(state, props))); | |
const createStructuredSelector = scheme => (state, props) => | |
Object.keys(scheme).reduce((result, key) => ({ | |
...result, | |
[key]: scheme[key](state, props) | |
}), {}); | |
// state example | |
const state = { | |
products: { | |
ids: [1, 2, 3], | |
entities: { | |
1: { id: 1, name: "Product 1" }, | |
2: { id: 2, name: "Product 2" }, | |
3: { id: 3, name: "Product 3" } | |
} | |
}, | |
basket: { | |
ids: [1, 3], | |
counts: { | |
1: 3, | |
3: 10 | |
} | |
} | |
}; | |
// base selectors | |
const getProductsIds = path(["products", "ids"]); | |
const getProductsEntities = path(["products", "entities"]); | |
const getBasketIds = path(["basket", "ids"]); | |
const getBasketCounts = path(["basket", "counts"]); | |
// some utils | |
const denormalize = (ids, entities) => | |
ids.map(id => entities[id]); | |
const createDenormalizeSelector = (getIds, getEntities) => | |
createSelector([getIds, getEntities], denormalize); | |
// complex selectors | |
const getProducts = createDenormalizeSelector(getProductsIds, getProductsEntities); | |
const getBasketProducts = createDenormalizeSelector(getBasketIds, getProductsEntities); | |
const getBasketProductsWithCount = createSelector( | |
[getBasketProducts, getBasketCounts], | |
(products, counts) => products.map(product => ({ | |
...product, | |
count: counts[product.id] | |
})) | |
); | |
// example | |
createStructuredSelector({ | |
products: getProducts, | |
basketIds: getBasketIds, | |
basketProducts: getBasketProductsWithCount | |
})(state, {}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
basketIds: [ | |
1, | |
3 | |
], | |
basketProducts: [ | |
{ | |
count: 3, | |
id: 1, | |
name: "Product 1" | |
}, | |
{ | |
count: 10, | |
id: 3, | |
name: "Product 3" | |
} | |
], | |
products: [ | |
{ | |
id: 1, | |
name: "Product 1" | |
}, | |
{ | |
id: 2, | |
name: "Product 2" | |
}, | |
{ | |
id: 3, | |
name: "Product 3" | |
} | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment