이제 등록과 무한스크롤 기능을 완성했으니
수정 + 삭제 기능이 남아있다.
수정 삭제에 대한 피그마의 지시사항이 따로 없어 내가 임의로 생각해내서 만들어보았다.
우선 삭제 기능부터 구현을 하였다.
삭제 기능은
홈페이지에서 각 목록들을 클릭을 하면 삭제할 것인지 수정할 것인지를 선택하는 모달 창을 띄우도록 만들었다.
그런 다음 삭제 로직을 찾아보았다.
삭제 api요청은 각 목록의 id값과 사용자가 입력한 비밀번호가 필요하다.
그러기 위해서는 우선
const [deleteId, setDeleteId] = useState(0);
const { userPassword } = usePassword();
각 목록을 클릭했을 때의 저장할 id 로컬변수와 주스탄드로 저장했었던 userPassword를 사용하려고 했다.
그렇다면 userPassword를 새로 입력해야하지 않을까??
맞다. 이전에 만들었던 비밀번호 입력 모달을 다시 띄워주기만 하면 비밀번호 값이 갱신되어진다.
그러고 난 뒤 비밀번호 입력이 완료되면 최종적으로 삭제가 실행된다.
정리를 하자면
그리고 구현하지 않았던 통신 기능들을 완료하였다.
import api from './base';
const deleteColorSurvey = async (id: number, password: string) => {
try {
const response = await api.delete(`/api/color-surveys/${id}`, {
data: {
password,
},
});
return response.data;
} catch (error) {
console.error('Error posting color surveys:', error);
throw error;
}
};
export default deleteColorSurvey;
매개변수로 id와 비밀번호를 받게 해주었고 엔드 포인트에는 id 바디에는 password를 넘겨주었다.
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { toast } from 'react-toastify';
import deleteColorSurvey from '../api/deleteColorSurvey';
import useFilterMbtiStore from '../store/filterMbtiStore';
const useDeleteMbtiColorMutation = () => {
const queryClient = useQueryClient();
const { filterMbti } = useFilterMbtiStore();
return useMutation({
mutationFn: ({ id, password }: { id: number; password: string }) => {
// postColorSurvey 호출 시에 매개변수를 전달
return deleteColorSurvey(id, password);
},
onSuccess: () => {
// 성공 시 처리
toast.success('삭제에 성공하였습니다.');
queryClient.invalidateQueries({ queryKey: ['getColorSurveys', filterMbti] });
},
onError: (error: any) => {
// 에러 처리
toast.error('삭제에 실패했습니다:', error);
},
});
};
export default useDeleteMbtiColorMutation;
삭제 성공 시에는 토스트로 사용자에게 알림을 제공하고 실시간으로 변경이 될 수 있도록 invalidateQueries를 하였다.