Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jungchris
Created April 11, 2017 02:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jungchris/14cd4f93370c3a3bd8901b428d72b741 to your computer and use it in GitHub Desktop.
Save jungchris/14cd4f93370c3a3bd8901b428d72b741 to your computer and use it in GitHub Desktop.
A Simple Redux Selector Example
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 }
@jungchris
Copy link
Author

@mileung
Copy link

mileung commented Jun 15, 2018

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