Skip to content

Instantly share code, notes, and snippets.

@alexfedoseev
Last active Aug 29, 2015
Embed
What would you like to do?
Redux: Reducer
/* app/bundles/app/reducers/comments.jsx */
import * as actionTypes from '../constants/CommentsConstants';
// Initial state of comments branch of the store
const initialState = {
type : null,
comments : [],
errors : null,
isPosting : false
};
// Input: state, action
export default function comments(state = initialState, action) {
// Action to variables
const { type, comment, errors } = action;
switch (type) {
// If COMMENT_ADD_REQUESTED
case actionTypes.COMMENT_ADD_REQUESTED:
// Updating state -> showing loader in component
return {
...state,
type,
isPosting: true
};
// If COMMENT_ADD_SUCCEED -> adding it to comments array
case actionTypes.COMMENT_ADD_SUCCEED:
// We should NEVER mutate state
// In complex apps we should use immutable.ls
// But here we're just creating a copy of `state.comments` array
let withNewComment = state.comments.slice();
// Unshifting new comment
withNewComment.unshift(comment);
// Updating state with new comment
return {
type,
comments : withNewComment,
errors : null,
isPosting: false
};
// If COMMENT_ADD_FAILED
case actionTypes.COMMENT_ADD_FAILED:
// Updating state with errors -> handling them in component
return {
...state,
type,
errors,
isPosting: false
};
default:
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment