import { ContainerState, ContainerActions, } from 'CommentSection/types'; import { FETCH_COMMENTS_SUCCESS, FETCH_USERS_SUCCESS, CREATE_COMMENT_SUCCESS, SET_THREAD_ID, DELETE_COMMENT_SUCCESS, SET_REPLY_USER, } from 'CommentSection/constants'; // The initial state of Comments export const initialState: ContainerState = { comments: [], users: [], threadId: '201808_AADS_1101', replyUser: '', }; function commentsReducer( state: ContainerState = initialState, action: ContainerActions, ): ContainerState { switch (action.type) { case SET_THREAD_ID: { return { ...state, threadId: action.payload.threadId, }; } case FETCH_COMMENTS_SUCCESS: { return { ...state, comments: action.payload.comments, }; } case CREATE_COMMENT_SUCCESS: { const commentData = action.payload.comment; const constructedComment = { id: '123', message: commentData.comment_text, author: 'Me', authorId: 'me', createdDate: (new Date).toString(), isOwner: true, }; const newComments = state.comments; newComments.unshift(constructedComment); return { ...state, comments: newComments, }; } case FETCH_USERS_SUCCESS: { return { ...state, users: action.payload.users, }; } case DELETE_COMMENT_SUCCESS: { const deletedCommentId = action.payload.comment.id; const newComments = state.comments.filter(c => deletedCommentId !== c.id); return { ...state, comments: newComments, }; } case SET_REPLY_USER: { const userString = action.payload.userString; return { ...state, replyUser: userString, }; } default: return state; } } export default commentsReducer;