React Query
json-server에 데이터 업데이트 하기 (patch)
내가 만들고자 한 기능은
작성한 게시물을 수정하는 기능이었다!
입력한 값을 모두 받아서 수정함수에 전달할 것이지만 put을 사용했을 경우
전달되지 않은 필드는 삭제된다고 한다.
그래서 전달되지 않은 필드가 있더라도 필드를 유지하도록 하기위해 patch를 사용했다.\
id와 password, date 필드는 게시글을 처음 작성한 시점부터 변경되지 않고,
유지되어야 하는 정보이기 때문에 수정된 전달 내용에 포함되지 않을 것이므로 patch가 적절하다!
해당 내용은 아래의 블로그를 참고했다!
https://redux-advanced.vlpt.us/3/01.html
3-1. json-server 이해하기 · GitBook
3-1 json-server 사용하기 json server 는 아주 짧은 시간에 REST API 를 구축해주는 라이브러리입니다. 하지만, REST API 서버의 기본적인 기능을 대부분 갖추고 있는데요, 프로덕션 전용은 아닙니다. 프로
redux-advanced.vlpt.us
axios로 서버와 통신하는 함수는 모두 posts.js에 따로 작성해두고,
export해서 필요한 컴포넌트에서 import해서 사용하도록 했다.
이렇게 하면 나중에 함수를 수정하기에도 편해진다!
post.js
// 조회
const getPosts = async () => {
const response = await axios.get("http://localhost:4000/posts");
return response.data;
};
// 삭제
const deletePost = async (id) => {
await axios.delete(`http://localhost:4000/posts/${id}`);
};
// 추가
const addPost = async (newTodo) => {
await axios.post("http://localhost:4000/posts", newTodo);
};
조회와 삭제, 추가는 어렵지 않게
get, delete, post를 사용해서 기능을 구현했다.
// 수정
const modifyPost = async (id, modifiedPost) => {
await axios.patch(`http://localhost:4000/posts/${id}`, modifiedPost);
console.log(modifiedPost);
};
그 밑에 수정함수를 만들어서
id와 수정된 post 내용인 modifiedPost 두 가지 인자를 받도록 설정했다.
modify 컴포넌트
const queryClient = useQueryClient();
const mutation = useMutation(modifyPost, {
onSuccess: () => {
queryClient.invalidateQueries("posts");
},
});
const updatePost = (e) => {
e.preventDefault();
let modifiedPost = posts.find((post) => post.id === id);
modifiedPost = { ...modifiedPost, body, userName, kcal, exerciseHour };
mutation.mutate(id, modifiedPost);
closeModal();
}
컴포넌트에서 수정버튼에 들어갈 함수 안에 mutate api를 사용했다.
이렇게 작성하면, modifiedPost 내용이 전달될 줄 알았는데,
계속 id값만 전달이 되고,
posts.js 에서 console.log(modifiedPost)를 하면 undefined로 확인되었다.
해결방법
posts.js
// 수정
const modifyPost = async ({ id, modifiedPost }) => {
await axios.patch(`http://localhost:4000/posts/${id}`, modifiedPost);
console.log(modifiedPost);
};
modify 컴포넌트
const updatePost = (e) => {
e.preventDefault();
let modifiedPost = posts.find((post) => post.id === id);
const confirmPassword = window.prompt("비밀번호를 입력하세요");
if (modifiedPost.password === confirmPassword) {
modifiedPost = { ...modifiedPost, body, userName, kcal, exerciseHour };
console.log(modifiedPost);
mutation.mutate({ id, modifiedPost });
closeModal();
alert("수정되었습니다!");
} else {
alert("비밀번호가 틀렸습니다!");
}
};
인자를 전달할때,
한 객체에 담아 전달하고,
구조분해할당으로 인자를 받으면 해결된다!
그리고 비밀번호 유효성 검증 절차를 추가했다.
prompt()로 비밀번호를 받아오고, json에 저장된 비밀번호와 비교하는 작업이다.
prompt앞에 window를 쓰지 않으면 warning이 계속 확인되어서 작성했다.