Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | import { CommentsState } from '@/types/hackernews';
import { Action } from '@/helpers/actionHelper';
import {
fetchComments,
fetchCommentsSuccess,
fetchCommentsFailure,
updateCommentItem,
resetComments,
} from './comments-actions';
const initialState: CommentsState = {
items: [],
loading: false,
error: null,
parentId: null,
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type CommentsAction = Action<any>;
const _fetchComments = (state: CommentsState, action: CommentsAction): CommentsState => ({
...state,
loading: true,
error: null,
parentId: action.payload,
});
const _fetchCommentsSuccess = (state: CommentsState, action: CommentsAction): CommentsState => ({
...state,
items: action.payload,
loading: false,
error: null,
});
const _fetchCommentsFailure = (state: CommentsState, action: CommentsAction): CommentsState => ({
...state,
loading: false,
error: action.payload,
});
const _updateCommentItem = (state: CommentsState, action: CommentsAction): CommentsState => {
const updatedItem = action.payload;
const itemIndex = state.items.findIndex((item) => item.id === updatedItem.id);
if (itemIndex === -1) {
return {
...state,
items: [...state.items, updatedItem],
};
}
const updatedItems = [...state.items];
updatedItems[itemIndex] = updatedItem;
return {
...state,
items: updatedItems,
};
};
const _resetComments = (): CommentsState => initialState;
type ReducerMap = {
[key: string]: (state: CommentsState, action: CommentsAction) => CommentsState;
};
const reducers: ReducerMap = {
[fetchComments.type]: _fetchComments,
[fetchCommentsSuccess.type]: _fetchCommentsSuccess,
[fetchCommentsFailure.type]: _fetchCommentsFailure,
[updateCommentItem.type]: _updateCommentItem,
[resetComments.type]: _resetComments,
};
const commentsReducer = (state = initialState, action: CommentsAction): CommentsState =>
reducers[action.type] ? reducers[action.type](state, action) : state;
export default commentsReducer;
|