reselect

Solutions on MaxInterview for reselect by the best coders in the world

showing results for - "reselect"
Manuel
11 Oct 2020
1import { createSelector } from 'reselect'
2
3const shopItemsSelector = state => state.shop.items
4const taxPercentSelector = state => state.shop.taxPercent
5
6const subtotalSelector = createSelector(
7  shopItemsSelector,
8  items => items.reduce((acc, item) => acc + item.value, 0)
9)
10
11const taxSelector = createSelector(
12  subtotalSelector,
13  taxPercentSelector,
14  (subtotal, taxPercent) => subtotal * (taxPercent / 100)
15)
16
17export const totalSelector = createSelector(
18  subtotalSelector,
19  taxSelector,
20  (subtotal, tax) => ({ total: subtotal + tax })
21)
22
23let exampleState = {
24  shop: {
25    taxPercent: 8,
26    items: [
27      { name: 'apple', value: 1.20 },
28      { name: 'orange', value: 0.95 },
29    ]
30  }
31}
32
33console.log(subtotalSelector(exampleState)) // 2.15
34console.log(taxSelector(exampleState))      // 0.172
35console.log(totalSelector(exampleState))    // { total: 2.322 }