Skip to content

Instantly share code, notes, and snippets.

@agoldis
Created April 28, 2018 23:41
Show Gist options
  • Select an option

  • Save agoldis/b4e752797b00a94e302e3cc40e550fea to your computer and use it in GitHub Desktop.

Select an option

Save agoldis/b4e752797b00a94e302e3cc40e550fea to your computer and use it in GitHub Desktop.
redux - full example
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