Files
astuto/app/javascript/reducers/postsReducer.ts

107 lines
2.4 KiB
TypeScript
Raw Normal View History

import IPost from '../interfaces/IPost';
import { FiltersState } from './filtersReducer';
import postReducer from './postReducer';
import filtersReducer from './filtersReducer';
import { POSTS_PER_PAGE } from '../constants';
import {
PostsRequestActionTypes,
POSTS_REQUEST_START,
POSTS_REQUEST_SUCCESS,
POSTS_REQUEST_FAILURE,
2022-05-07 11:27:07 +02:00
} from '../actions/Post/requestPosts';
2022-05-07 11:27:07 +02:00
import { postRequestSuccess } from '../actions/Post/requestPost';
2019-09-12 15:51:45 +02:00
import {
ChangeFiltersActionTypes,
SET_SEARCH_FILTER,
SET_POST_STATUS_FILTER,
} from '../actions/changeFilters';
2019-09-27 16:57:23 +02:00
import {
LikeActionTypes,
LIKE_SUBMIT_SUCCESS,
2022-05-07 11:27:07 +02:00
} from '../actions/Like/submitLike';
2019-09-27 16:57:23 +02:00
export interface PostsState {
items: Array<IPost>;
page: number;
haveMore: boolean;
areLoading: boolean;
error: string;
filters: FiltersState;
}
const initialState: PostsState = {
items: [],
page: 0,
haveMore: true,
areLoading: false,
error: '',
2019-09-26 16:03:41 +02:00
filters: filtersReducer(undefined, {} as ChangeFiltersActionTypes),
};
const postsReducer = (
state = initialState,
2019-09-27 16:57:23 +02:00
action:
PostsRequestActionTypes |
ChangeFiltersActionTypes |
LikeActionTypes,
): PostsState => {
switch (action.type) {
case POSTS_REQUEST_START:
return {
...state,
areLoading: true,
};
case POSTS_REQUEST_SUCCESS:
return {
...state,
items: action.page === 1 ?
2019-09-12 15:51:45 +02:00
action.posts.map(post => postReducer(undefined, postRequestSuccess(post)))
:
2019-09-12 15:51:45 +02:00
[...state.items, ...action.posts.map(post => postReducer(undefined, postRequestSuccess(post)))],
page: action.page,
haveMore: action.posts.length === POSTS_PER_PAGE,
areLoading: false,
error: '',
};
case POSTS_REQUEST_FAILURE:
return {
...state,
areLoading: false,
error: action.error,
};
case SET_SEARCH_FILTER:
case SET_POST_STATUS_FILTER:
return {
...state,
filters: filtersReducer(state.filters, action),
};
2019-09-27 16:57:23 +02:00
case LIKE_SUBMIT_SUCCESS:
return {
...state,
items: state.items.map(post => {
if (action.postId === post.id) {
return action.isLike ?
{ ...post, likesCount: post.likesCount + 1, liked: 1 }
:
{ ...post, likesCount: post.likesCount - 1, liked: 0 }
} else return post;
}),
};
default:
return state;
}
}
export default postsReducer;