컴포넌트의 UI가 잘 만들어진 것을 확인했다면 useMutation을 사용하여 댓글을 작성하고, useQueryClient를 사용하여 댓글 목록을 갱신해봅시다.

    components/CommentInput.tsx

    import React, {useState} from 'react';
    import {StyleSheet, Text, Pressable} from 'react-native';
    import {useMutation, useQueryClient} from 'react-query';
    import {writeComment} from '../api/comments';
    import {Comment} from '../api/types';
    import CommentModal from './CommentModal';
    
    export interface CommentInputProps {
      articleId: number;
    }
    
    function CommentInput({articleId}: CommentInputProps) {
      const [writingComment, setWritingComment] = useState(false);
      const queryClient = useQueryClient();
      const {mutate} = useMutation(writeComment, {
        onSuccess: (comment) => {
          queryClient.setQueryData<Comment[]>(['comments', articleId], (comments) =>
            (comments || []).concat(comment),
          );
        },
      });
    
      const onPress = () => {
        setWritingComment(true);
      };
      const onClose = () => {
        setWritingComment(false);
      };
      const onSubmit = (message: string) => {
        setWritingComment(false);
        mutate({
          articleId,
          message,
        });
      };
      return (
        <>
          <Pressable style={styles.block} onPress={onPress}>
            <Text style={styles.text}>댓글을 입력하세요</Text>
          </Pressable>
          <CommentModal
            onClose={onClose}
            visible={writingComment}
            onSubmit={onSubmit}
          />
        </>
      );
    }
    
    (...)

    여기까지 코드를 작성하고 나서, 댓글을 입력 후 키보드의 Enter를 눌러보세요. 댓글 목록이 잘 갱신됐나요?

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.