React Query를 이용해 ToDo List를 만들기 2

zaman·2022년 11월 15일
1

Toy Projects

목록 보기
6/6
post-thumbnail

React Query를 이용해 ToDo List를 만들기 1

이번엔 추가, 수정, 삭제를 구현하는 법을 포스팅해보려고 한다.
빨리 올렸어야했는데 요즘 정신이 없어서 포스팅이 밀렸다ㅠ

코드는 React Query를 이용해 ToDo List를 만들기 1과 동일한 Todos.tsx 파일에 작성했다.

코드를 살펴보기 전 먼저 사용한 리액트쿼리 함수를 살펴보자

useQueryClient()

: The useQueryClient hook returns the current QueryClient instance.
: QueryClient 인스턴스를 반환

import { useQueryClient } from '@tanstack/react-query'

const queryClient = useQueryClient({ context })

Options

context?: React.Context<QueryClient | undefined>
: Use this to use a custom React Query context. Otherwise, defaultContext will be used.
: 사용자 정의 리액트 쿼리 컨텍스트를 사용하려면 이렇게 사용 아니면 디폴트인 defaultContext가 사용됨

useMutation()

공식문서 useMutaion()
https://tanstack.com/query/v4/docs/reference/useMutation

Mutation : 변화, 변이
이름처럼 직관적으로 값을 바꿀 때 사용(데이터 생성, 수정, 삭제)
공식 홈페이지에 보면 옵션이 굉장히 많은데 일단 사용한 옵션만 언급하고 나머지는 다음에 정리해서 올려보려고 한다.

onSuccess: (data: TData, variables: TVariables, context?: TContext) => Promise<unknown> | void

mutation 성공, 결과를 전달할 때 실행

onError: (err: TError, variables: TVariables, context?: TContext) => Promise<unknown> | void

mutation이 error 를 만났을 때 실행

➕ todo 생성(추가)

export function useCreateTodo() {
  const queryClient = useQueryClient();
  return useMutation((todo: ITodo) => ToDoAPI.create(todo), {
    onSuccess: () => {
      queryClient.invalidateQueries(Keys.all);
    },
  });
}

invaildate queries: queryKey의 유효성을 제거해주는 목적으로 사용
➡️ 왜 제거? 서버로부터 데이터를 다시 조회해오기 위해

사용전에는 AddTodo.tsx에서 이런식으로 사용했다면

const onhandleAdd = async (event: React.MouseEvent<HTMLElement>) => {
    event.preventDefault();
    const todo = {
      title: TitleRef.current!.value,
      content: ContentRef.current!.value,
    };

await ToDoAPI.create(token, todo) 
  		// handleAddList는 Todos.tsx에서 props로 받은 함수
        .then((res) => handleAddList(res.data.data));
      setOption("success"); // success alert
    } catch (err) {
      setOption("fail"); // error alert
    }

Todos.tsx에 있는 handleAddList --> todos의 List state를 변경하기 위해 이렇게 사용했었음

  const handleAddList = (todo: ListType) => {
    const newList = [...list, todo];
    setList(newList);
  };

지금은 더 간단하고 파악하기 쉽게 사용할 수 있다.

 const create = useCreateTodo();
 const { mutateAsync, isLoading } = create;
 
 // 코드 생략

const onhandleAdd = async (event: React.MouseEvent<HTMLElement>) => {
    event.preventDefault();
    const todo = {
      title: TitleRef.current!.value,
      content: ContentRef.current!.value,
    };

    try {
      await mutateAsync(todo);
      setOption("success"); // success alert
    } catch (err) {
      setOption("fail"); // error alert
    }
  };

수정과 삭제도 마찬가지

🛠 todo 수정

export function useUpdateToDo(id: string) {
  const queryClient = useQueryClient();
  return useMutation((todo: ITodo) => ToDoAPI.update(id, todo), {
    onSuccess: () => queryClient.invalidateQueries(Keys.all),
  });
}

🗑 todo 삭제

export function useDeleteToDo(id: string) {
  const queryClient = useQueryClient();
  return useMutation(() => ToDoAPI.del(id), {
    onSuccess: () => queryClient.invalidateQueries(Keys.all),
  });

기본 기능이라 생각보다 간단했다


다음은 마지막으로 리액트 쿼리 복습 + 정리!

profile
개발자로 성장하기 위한 아카이브 😎

0개의 댓글