Created
April 11, 2017 02:17
-
-
Save jungchris/14cd4f93370c3a3bd8901b428d72b741 to your computer and use it in GitHub Desktop.
A Simple Redux Selector 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
import { createSelector } from 'reselect' | |
const shopItemsSelector = state => state.shop.items | |
const taxPercentSelector = state => state.shop.taxPercent | |
const subtotalSelector = createSelector( | |
shopItemsSelector, | |
items => items.reduce((acc, item) => acc + item.value, 0) | |
) | |
const taxSelector = createSelector( | |
subtotalSelector, | |
taxPercentSelector, | |
(subtotal, taxPercent) => subtotal * (taxPercent / 100) | |
) | |
export const totalSelector = createSelector( | |
subtotalSelector, | |
taxSelector, | |
(subtotal, tax) => ({ total: subtotal + tax }) | |
) | |
let exampleState = { | |
shop: { | |
taxPercent: 8, | |
items: [ | |
{ name: 'apple', value: 1.20 }, | |
{ name: 'orange', value: 0.95 }, | |
] | |
} | |
} | |
console.log(subtotalSelector(exampleState)) // 2.15 | |
console.log(taxSelector(exampleState)) // 0.172 | |
console.log(totalSelector(exampleState)) // { total: 2.322 } |
Thanks. I just wanted to learn what Redux Selectors were at the fundamental level and every description I saw online was like an entire chapter in a novel. This code explains selectors pretty well imo...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Document source is: https://github.com/reactjs/reselect