본문 바로가기

Else/Personal Blog Building

Beomlog - Posts by Category

이번에는 카테고리별로 post들을 가져오는 메서드를 만들도록 하겠다. 이 역시 리덕스와 리덕스 미들웨어로 구성할 것이다.

 

하지만 posts들을 가져오는 것은 마치 userData를 가져오는 것과 비슷하다. post처럼 복잡하게 CRUD모두가 필요한 것이 아니라, R와 D만 있으면 된다. 나머지는 post를 업로드 할때 자동으로 처리를 해주기 때문에, 게시물들을 한눈에 볼 수 있는 R과 게시물들을 상태에서 지워주는 D만 있으면 된다. 한번 해보도록 하자.

 

import { category } from "../Container/Home/HeaderContainer";
import { createCategoryPostsSaga } from "../lib/asyncUtils";
import { takeEvery } from "redux-saga/effects";
import { getCategoryPostsFromDatabase } from "../api/firebase";


const GET_POSTS = 'categoryPosts/GET_POSTS';
const GET_POSTS_SUCCESS = 'categoryPosts/GET_POSTS_SUCCESS';
const GET_POSTS_ERROR = 'categoryPosts/GET_POSTS_ERROR';

const DELETE_POSTS = 'categoryPosts/DELETE_POSTS';

export type getCategoryPostsParams = {
    uid: string,
    category: string
};
export const getCategoryPosts = (params: getCategoryPostsParams) => ({
    type: GET_POSTS,
    payload: params
});
export const deleteCategoryPosts = () => ({
    type: DELETE_POSTS
})

////////// state ////////////////////
type categoryPost = {
    category: string;
    editorData: string;
    postId: string;
    time: any;
    title: string;
    userData: {
        email: string,
        name: string,
        imgUrl: string,
        categories: {
            [category: string]: category
        }
    };
}
export type CategoryPostsState = categoryPost[]
const initialState: CategoryPostsState = [];

//////////// saga ////////////////////////////

const getCategoryPostsSaga = createCategoryPostsSaga(GET_POSTS, getCategoryPostsFromDatabase);

export function* categoryPostsSaga() {
    yield takeEvery(GET_POSTS, getCategoryPostsSaga);
}

////////// reducer ////////////////////////////


export default function categoryPosts(state: CategoryPostsState = initialState, action: any): CategoryPostsState {
    switch(action.type) {
        case GET_POSTS:
            return initialState;
        case GET_POSTS_SUCCESS:
            return action.payload;
        case GET_POSTS_ERROR:
            return initialState;
        case DELETE_POSTS:
            return initialState;
        default:
            return state;
    }
}

categoryPosts 리덕스는 이와 같이 구현했고, getCategoryPostsFromDatabase는 이렇게 구현했다.

그 후, CategoryPostsList 라는 컴포넌트는 이렇게 구현했으며,

이후 실행해보면,

 

아주 잘 실행된다. 이제 정말로 꾸미기만 하고 몇가지만 더 고치면 끝이다!