Skip to content

Instantly share code, notes, and snippets.

@emilong
Last active May 18, 2016 18:34
Show Gist options
  • Save emilong/1c5d23c6a2ec000bca630298435c0bfd to your computer and use it in GitHub Desktop.
Save emilong/1c5d23c6a2ec000bca630298435c0bfd to your computer and use it in GitHub Desktop.
import { combineReducers } from 'redux'
import { createAction, handleActions } from 'redux-actions'
const authorFetched = createAction('AUTHOR_FETCHED')
const bookFetched = createAction('BOOK_FETCHED')
const literaryReducer = handleActions({
// maybe an author has a bunch of books as sub-resources
AUTHOR_FETCHED: (state, action) => {
const author = action.payload
const { books } = author
const authors = Object.assign({}, state.authors, { [author.id]: author })
const books = Object.assign({}, state.books, books)
return { authors, books }
},
// a book has an author sub-resource
BOOK_FETCHED: (state, action) => {
const book = action.payload
const { author } = book
const authors = Object.assign({}, state.authors, { [author.id]: author })
const books = Object.assign({}, state.books, { [book.id]: book })
return { authors, books }
},
}, {
authors: {},
books: {},
})
export const authorSelector = id => state => state.literary.authors[id]
export const bookSelector = id => state => state.literary.books[id]
export default combineReducers({
literary: literaryReducer,
otherStuff: otherReducer,
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment