(TodoDetail.jsx)
const [toggle, setToggle] = useState(false)
const editToggleHandler = () => {
toggle ? setToggle(false) : setToggle(true)
}
// useState 받고 toggle을 변수로 사용한 함수 지정 후 아래에 적용(삼항연산자)
...
...
{toggle ? (<StEditContainer>
<textarea style={{width:300, height:200 }}
type="text"
maxLength={200}
placeholder="수정본문값 입력"
onChange={(event) => {
setEditTodo({
...editTodo,
body: event.target.value,
});
}}
/>
<StEditButton type="button"
borderColor="#ddd" onClick={onClickEditButtonHandler}>
본문수정
</StEditButton>
</StEditContainer>) : null}
// 데이터 직접 고치려면 axios 사용해야해서 낭비가 된다.
(Comments.jsx)
const [comment, setComment] = useState({
id : 0,
writer : "",
body : ""
})
const [commentList, setCommentList] = useState([])
const fetchComments = async () => {
const { data } = await axios.get("http://localhost:3001/comments");
const selCommentList = data.filter((val) => {
return Number(props.id) === Number(val.commentId)})
// detail id랑 axios id랑 비교
// 새로고침해야 값 나오는 것 해결? : useEffect로 해결
setCommentList(selCommentList);
};
useEffect(() => {
fetchComments()
}, [commentList]);
...
...
(Comments.jsx)
const onSubmitHandler = (event) => {
// 전송버튼
event.preventDefault();
if (
comment.body.trim() === "" ||
comment.writer.trim() === ""
) {
return alert("모든 항목을 입력해주세요.");
}
const obj = {
commentId : props.id,
id:getMaxId()+1,
body: comment.body,
writer: comment.writer,
};
// addTodo 더할 때는 형태에 맞게 더하기
// try-catch문 필요 :
axios.post("http://localhost:3001/comments", obj);
dispatch(addComments(comment));
// 입력란 공백을 위한 공객체 생성
setComment({
writer: "",
body: "",
});
}
addTodo와 구조 유사
(Comments.jsx)
const [editComment, setEditComment] = useState({
body : ""
});
const onClickEditButtonHandler = async(id) => {
const res = await axios.patch(`http://localhost:3001/comments/${id}`, {body : editComment.body});
setCommentList([{
...commentList,
body : res.data.body
}])
}
// json 서버 내용 async await, axios 이용하여 접근. patch로 값 바꾼 뒤 다시 저장하는 것
(Comments.jsx)
const onClickDelButtonHandler = async(id) => {
const res = await axios.delete(`http://localhost:3001/comments/${id}`, {body : editComment.body});
}
...
...
<StEditButton type="button" onClick={()=>{const result = window.confirm("이 댓글을 지울까요?");
if (result) {
return onClickDelButtonHandler(item.id);
} else {
return;
}}}>삭제</StEditButton>
// 삭제 시 한 번 더 물어봐주기
const [toggle, setToggle] = useState(false)
const editToggleHandler = (index) => {
setToggle(index)
// index로 값을 찾아서 넣는다.
}
이건 타입스크립트에서 더 자세히 다뤄도 된다.
과제 요구사항에 맞춰라. + 보완(성크 등)
e.g. 스토어 스테이트 분리