Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

jungchris commented Apr 11, 2017

@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