[react query] 리액트쿼리 도입하기 (2)

KoEunseo·2023년 4월 28일
0

project

목록 보기
33/37

1. index.js

provider에 query client 등록.
고민하다가 redux보다 상위에 두었다.
리액트쿼리는 server data를 관리할 거니까.

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();
... 생략 ..
    <QueryClientProvider client={queryClient}>
      <Provider store={store}>
        <PersistGate loading={null} persistor={persistor}>
          <BrowserRouter>
            <GlobalStyle />
            <App />
          </BrowserRouter>
        </PersistGate>
      </Provider>
    </QueryClientProvider>
...생략 ...

2. Friend

refresh 걷어내고 useQuery로 대체
리액트쿼리 도입

before : addFriend

import { useEffect, useState } from 'react';

const AddFriend = ({ setIsOpen, friends, setfriendRefresh }: AddFriendType) => {
  const [userList, setUserList] = useState([]);
  const [keyword, bindKeyword] = useInput('');
  const [respondentDisplayName, setRespondentDisplayName] = useState('');
  const requesterDisplayName = useSelector(displayNameSelector);

  useEffect(() => {
    const fetchData = async () => {
      const data = await getAllMembers();
      setUserList(data);
    };
    fetchData();
  }, []);

  const CloseModal = () => {
    setIsOpen(false);
  };

  const filteredMember = userList?.filter(member => {
    const friendsNameArr = friends.map(friend => {
      return friend.respondentDisplayName;
    });
    return (
@@ -50,9 +51,18 @@ const AddFriend = ({ setIsOpen, friends, setfriendRefresh }: AddFriendType) => {
    );
  });

  const handleAddFriend = () => {
    addFriend({ requesterDisplayName, respondentDisplayName });
    setfriendRefresh(refresh => refresh * -1);
    toast('친구를 추가했어요!');
  };

after

import { useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';

const AddFriend = ({ setIsOpen, friends, setfriendRefresh }: AddFriendType) => {
  const [keyword, bindKeyword] = useInput('');
  const [respondentDisplayName, setRespondentDisplayName] = useState('');
  const requesterDisplayName = useSelector(displayNameSelector);

  const userList = useQuery({
    queryKey: ['user'],
    queryFn: async () => {
      const data = await getAllMembers();
      return data;
    },
  });

  const CloseModal = () => {
    setIsOpen(false);
  };

  const filteredMember = userList?.data?.filter(member => {
    const friendsNameArr = friends?.map(friend => {
      return friend.respondentDisplayName;
    });
    return (
@@ -50,9 +51,18 @@ const AddFriend = ({ setIsOpen, friends, setfriendRefresh }: AddFriendType) => {
    );
  });

  const mutation = useMutation({
    mutationFn: (args: AddFriendArg) => {
      const { requesterDisplayName, respondentDisplayName } = args;
      return addFriend({ requesterDisplayName, respondentDisplayName });
    },
  });
  const handleAddFriend = () => {
    mutation.mutate({ requesterDisplayName, respondentDisplayName });
    toast('친구를 추가했어요!');
  };

3. 그런데 UI에 바로바로 적용이 안되네?

queryClient.invalidateQueries(['friend']); 추가

import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (args: AddFriendArg) => {
      const { requesterDisplayName, respondentDisplayName } = args;
      return addFriend({ requesterDisplayName, respondentDisplayName });
    },
    onSuccess: () => {
      queryClient.invalidateQueries(['friend']);
    },
  });
  const handleAddFriend = () => {
    mutation.mutate({ requesterDisplayName, respondentDisplayName });

제대로 작동 하고 있다 ^____^ 데이터가 캐싱되어있어서 변경되지 않았던 것...
기능을 만들어가는 것도 재미있지만 이렇게 리팩토링하는 것도 정말 뿌듯하고 재미있다.
제대로 작동할때의 그 쾌감이란ㅎㅎ

profile
주니어 플러터 개발자의 고군분투기

0개의 댓글