📌
게임로직이 어느정도 안정화 되어 커뮤니티 페이지를 구현하게 되었는데요! 😊
제가 맡은 부분은 게시글 (POST) CRUD 기능 입니다!
CREATE 기능은 이전 게시글에서 확인할수 있습니다!
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import { Link, useParams, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from 'react-redux';
// 내부 모듈
import backBtn from 'assets/images/backBtn.svg';
import okBtn from 'assets/images/okBtn.svg';
import { updatePost, readOnePost } from 'redux/modules/postSlice';
function ModifyPost() {
const post = useSelector((state) => state.posts.posts);
const param = useParams();
const dispatch = useDispatch();
const [content, setContent] = useState(post.content);
const [title, setTitle] = useState(post.title);
const [imgs, setImgs] = useState([]);
const navigate = useNavigate();
const handleImage = (event) => {
const imageLists = [];
for (let i = 0; i < event.target.files.length; i += 1) {
imageLists.push(event.target.files[i]);
}
console.log(imageLists);
setImgs(imageLists);
};
function modifyPost() {
const post = {
content,
title,
};
dispatch(updatePost({ post, imgs, postId: param.id }));
}
useEffect(() => {
dispatch(readOnePost(param.id));
}, []);
return (
<StWritePost>
<StWritePostHeader>
<Link to="/posts/all">
<StBackBtn>
<img src={backBtn} alt="뒤로 가기" />
</StBackBtn>
</Link>
<StTitle>게시글 수정</StTitle>
</StWritePostHeader>
<StInputBox>
<input
type="file"
multiple
accept="image/*"
onChange={(e) => {
handleImage(e);
}}
/>
</StInputBox>
<StPostSection>
<StTitleArea
value={title}
onChange={(e) => {
setTitle(e.target.value);
}}
/>
<StContentArea
value={content}
onChange={(e) => {
setContent(e.target.value);
}}
/>
</StPostSection>
<StWritePostBtn type="button" onClick={modifyPost}>
<img src={okBtn} alt="확인" />
</StWritePostBtn>
</StWritePost>
);
}
export const updatePost = createAsyncThunk(
'post/UPDATE_POST',
async (payload, thunkAPI) => {
try {
const formData = new FormData();
const json = JSON.stringify(payload.post);
const blob = new Blob([json], { type: 'application/json' });
formData.append('data', blob);
for (let i = 0; i < payload.imgs.length; i += 1) {
formData.append('file', payload.imgs[i]);
}
const response = await instance.put(
`/posts/${payload.postId}`,
formData,
{
headers: {
'Content-Type': 'multipart/form-data',
},
},
);
console.log('res', response);
return thunkAPI.fulfillWithValue(response.data);
} catch (error) {
return thunkAPI.rejectWithValue(error);
}
},
);
☝
다음 게시글에선 delete를 살펴보겠습니다 :)