src > api > todos.js
import axios from "axios";
const SERVER_URI = "http://localhost:4000";
const getTodos = async () => {
const response = await axios.get(`${SERVER_URI}/todos`);
return response.data;
};
const addTodo = async (newTodo) => {
await axios.post(`${SERVER_URI}/todos`, newTodo);
};
const removeTodo = async (id) => {
await axios.delete(`${SERVER_URI}/todos/${id}`);
};
const switchTodo = async (payload) => {
await axios.patch(`${SERVER_URI}/todos/${payload.id}`, {
isDone: payload.isDone,
});
};
export { getTodos, addTodo, removeTodo, switchTodo };
src > query > useTodosQuery.js
방법 1)
import { useMutation } from "react-query";
import { addTodo, removeTodo, switchTodo } from "../api/todos";
const useTodosQuery = () => {
const addMutation = useMutation(addTodo);
const removeMutation = useMutation(removeTodo);
const switchMutation = useMutation(switchTodo);
return { addMutation, removeMutation, switchMutation };
};
export default useTodosQuery;
방법 2)
import { useMutation } from "react-query";
import { addTodo, removeTodo, switchTodo } from "../api/todos";
export const useAddMutation = () => useMutation(addTodo);
export const useRemoveMutation = () => useMutation(removeTodo);
export const useSwitchMutation = () => useMutation(switchTodo);
src > query > keys.constant.js
export const KEY_QUERY = {
TODOS: "todos",
};
import { getTodos } from "../../../api/todos";
import { KEY_QUERY } from "../../../query/keys.onstant";
...
const { isLoading, isError, data: todos } = useQuery(KEY_QUERY.TODOS, getTodos);
const { addMutation } = useTodosQuery();
const { mutate: addMutate } = addMutation;
cosnt { addMutaion: {mutate: addMutate} } = useTodosQuery();
addMutate(newTodo, {
onSuccess: (data) => {
console.log("data", data);
queryClient.invalidateQueries(KEY_QUERY.TODOS);
},
이와 같이 컴포넌트를 분리하여 사용해주면 재사용성이 높아지고 가독성도 좋아진다는 장점이 있었다. useQuery를 사용할 때 구현할 함수가 많아진다면 꼭 분리해서 사용하는 것이 좋을 것 같다.