[프론트]리덕스를 활용한 스크랩 기능 구현

hansoom·2023년 3월 20일
0

redux

목록 보기
1/7
post-thumbnail

✍리덕스로 스크랩 기능 구현

💡리덕스 scrapSlice 정의

  • app 폴더 > store.js
export const store = configureStore({
    reducer: {
        scrap: scrapSlice.reducer,
    },
});
  • features 폴더 > scrapSlice.js
import { createSlice } from '@reduxjs/toolkit';

export const scrapSlice = createSlice({
	name: 'scrap',
	initialState: { 
        posts: [], 
    },
	reducers: {
		addScrap(state, action) {
            const newPost = action.payload;
			state.posts.push({
                image: newPost.image,
                id: newPost.id,
                title: newPost.title,
                location: newPost.location,
                board: newPost.board,
            });
		},
        removeScrap(state,action){
            const id = action.payload;
            state.posts = state.posts.filter((post) => post.id !== id);
        },
	},
});

export const scrapActions = scrapSlice.actions;
export default scrapSlice;

posts배열에 스크랩할 게시글을 저장해놓는다
addScrap action은 해당 게시글의 정보들을 posts배열에 push 매소드를 활용하여 추가시킨다
removeScrap action은 해당 게시글의 정보를 filter 메소드를 활용하여 제거한다

💡리덕스 데이터 활용

  • 스크랩 마이페이지 컴포넌트
export default function Userpost({id, image, title, location, board}) {
    const dispatch = useDispatch();
    const handleDelete = () => {
        alert('삭제하시겠습니까?')
        dispatch(scrapActions.removeScrap(image));
    }
    return (
        <div className="userpost">
            <img src={image} alt="" />
            <h5>{board} 게시판{id}</h5>
            <h6>위치: {location}</h6>
            <h6>제목: {title}</h6>
            <div className="userpost_delete" onClick={handleDelete}>
                <h6><DeleteIcon /></h6>
                <h6>삭제하기</h6>
            </div>
        </div>
    );
}

삭제하기 버튼을 누르면 handleDelete 함수를 통해 removeScrap action을 dispatch 한다.

  • 스크랩한 게시글 출력해주는 컴포넌트
export default function Userinfo() {
    const scrapPosts = useSelector((state) => state.scrap.posts);
    return (
    	<div className="userinfo">
        	<div className="userposts">
            	{scrapPosts.map((scrap) => (
                	<Userpost
                    	id={scrap.id}
                        image={scrap.image} 
                        title={scrap.title} 
                        location={scrap.location} 
                        board={scrap.board} 
                    />
                ))}
            </div>
        </div>
    );
}

useSelector 를 활용해 리덕스 데이터를 가져온 후 이를 map을 통해 posts 배열에 저장되어 있는 게시글 정보들을 Userpost 컴포넌트에 props로 전달해준다

  • 스크랩한 게시글의 개수 출력
const scrapPosts = useSelector((state) => state.scrap.posts);
let scrapCount = Object.keys(scrapPosts).length
return (<h5>{scrapCount}</h5>)
  • 스크랩 하는 함수 정의
const handleScrap = () => {
        alert('스크랩하시겠습니까?');
        postList.forEach((post) => {
            dispatch(scrapActions.addScrap({
                writer: post.writer,
                image: post.image,
                id: post.id,
                title: post.title,
                location: post.location,
                board: "find",
            }))
        })
    }

0개의 댓글