Last active
November 6, 2020 10:10
-
-
Save kubk/c64a8a7755ea090a7d775e000c91bbe5 to your computer and use it in GitHub Desktop.
Mobx VS Reselect comparison
This file contains 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
const store = makeAutoObservable({ | |
shop: { | |
taxPercent: 8, | |
items: [ | |
{ name: 'apple', value: 1.20 }, | |
{ name: 'orange', value: 0.95 }, | |
] | |
}, | |
get subtotal() { | |
return this.shop.items.reduce((acc, item) => acc + item.value, 0); | |
}, | |
get tax() { | |
return this.subtotal * (this.shop.taxPercent / 100) | |
}, | |
get total() { | |
return { total: this.subtotal + this.tax } | |
} | |
}) | |
console.log(store.subtotal) // 2.15 | |
console.log(store.tax) // 0.172 | |
console.log(store.total) // { total: 2.322 } |
This file contains 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
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 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment