Created
April 28, 2018 23:41
-
-
Save agoldis/b4e752797b00a94e302e3cc40e550fea to your computer and use it in GitHub Desktop.
redux - full 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 { compose } from "redux"; | |
| import { createSelector } from "reselect"; | |
| const getBooks = state => state.books; | |
| const getUsers = state => state.users; | |
| const getComments = state => state.comments; | |
| const usersSummary = createSelector( | |
| [getUsers, getComments], | |
| (users, comments) => | |
| users.map(user => ({ | |
| ...user, | |
| booksCount: user.books.length, | |
| commentsCount: comments.filter(c => c.user === user.id).length | |
| })) | |
| ); | |
| const booksSummary = createSelector( | |
| [getBooks, getUsers, getComments], | |
| (books, users, comments) => | |
| books.map(book => ({ | |
| ...book, | |
| readersCount: users.filter(u => u.books.indexOf(book.isbn) > -1).length, | |
| commentsCount: comments.filter(c => c.book === book.isbn).length | |
| })) | |
| ); | |
| const addUsersSummary = state => | |
| Object.defineProperty(state, "usersSummary", { | |
| get: () => usersSummary(state), | |
| enumerable: false, | |
| configurable: true | |
| }); | |
| const addBooksSummary = state => | |
| Object.defineProperty(state, "booksSummary", { | |
| get: () => booksSummary(state), | |
| enumerable: false, | |
| configurable: true | |
| }); | |
| export const deriveState = compose( | |
| addBooksSummary, | |
| addUsersSummary | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment