Skip to content
Sleepingoff edited this page Nov 2, 2023 · 3 revisions

Recoil 이용해서 검색어 저장하기

상황

  • 검색바는 헤더에 있고, 리스트박스는 메인에 있다.
  • PageTemplate을 사용하여 헤더는 한 곳에서 관리한다. 즉, 헤더가 메인의 상태를 모른다.
  • 검색에 change 이벤트가 일어나면 실시간으로 데이터 필터링을 해줘야 한다.

개념

  1. Recoil에 저장하기 위해 아톰을 만들자! 📂src/store/queryAtom.js
import { atom } from "recoil";

const queryAtom = atom({
    key: 'query',
    default: "",
});

export default queryAtom;
  1. 입력하는 검색어를 아톰에 저장하자! 📂src/components/layout/Header.jsx
import React, { useState } from "react";
import SearchBar from "../searchbar/searchbar";
import { useLocation } from "react-router";
import queryAtom from "../../store/queryAtom";
import { useRecoilState } from "recoil";

const Header = () => {
    const [query, setQuery] = useState("");
   //👇 useState와 사용법이 비슷한 이것이 바로 아톰에 값을 저장하게 해줌!
    const [queries, setQueries] = useRecoilState(queryAtom);
    
    const handleChangeQuery = (event) => {
        setQuery(event.target.value)
        setQueries(query);
    }

    //메인의 상태를 모르기 때문에 url을 사용하여 placeholder를 바꿔줌
    const { pathname } = useLocation();
    let placeholder;
    switch(pathname.split('/')[1]){
        case 'main':
            placeholder = `지하철역을 검색해주세요!`;
            break;
        case 'feed':
            placeholder = `유저를 검색해주세요`;
            break;
        default:
            placeholder = `검색어를 입력해주세요!`
    }

    return (
        <header>
        <SearchBar placeholder={placeholder} onChange={handleChangeQuery} value={query}/>
        </header>
    )
}

export default Header;
  1. 저장한 검색어를 사용하자! 📂src/views/Home.view.jsx
import React, {useState, useEffect}  from "react";
import PageTemplate from "../components/PageTemplate";
import { useRecoilValue } from "recoil";
import queryAtom from "../store/queryAtom";

const HomePage = () => {
  //전역에 저장한 검색어 꺼내오기
  const query = useRecoilValue(queryAtom);
  console.log(query);

  //생략

  useEffect(()=>{
    setPosts(data?.data.post);
  }, [!isLoading])

  return(
    <PageTemplate>
      //생략
    </PageTemplate>
  )
}

export default HomePage;

결론

atom 만들고 해당 아톰을 키로 하여 상태를 저장하고 꺼내올 수 있다.

useRecoilState(atom) 저장할 상태가 있는 곳에 선언해주고 useState처럼 사용하기

useRecoilValue(atom) 상태를 사용할 곳에 선언하여 사용가능~

리액트 쿼리 적용하기

상황

  • 게시글, 댓글 등 서버의 데이터에서 필터하여 가져와야 하는 데이터 혹은 자주 바뀌는 데이터를 관리해야 한다.
  • 무한 스크롤을 적용해야 한다.
  • 현재 반복문을 사용하여 적용하였기에 속도가 느리다.

개념

  1. axios를 반환하는 api 함수를 만들자! 📂src/api/postComment.js
import client from '../config/api.config';

const postCommentList = async (postId, content) => {
  const comment = {
    comment: {
      content: content,
    },
  };
  const token = JSON.parse(localStorage.getItem('user')).token;
  return await client.post(`/post/${postId}/comments`, comment, client.BothType(token));
};
  1. 해당 함수를 사용하는 쿼리키를 만들자! 📂src/api/postComment.js
const commentListQuery = (postId, content) => ({
  mutationKey: ['post', 'commentList', postId],
  mutationFn: async () => postCommentList(postId, content),
});

export default commentListQuery;

1번과 같은 파일에서 만들고, 해당 api를 사용할 때는 만들어놓은 쿼리키를 사용하면 된다! 여기에서는 post 메서드를 사용하기 때문에 mutation으로 등록하였다.

  1. 이제 직접 사용해보자! 📂src/views/Feed.view.jsx
import { useNavigate, useParams } from 'react-router';
//생략
import { useMutation } from '@tanstack/react-query';
import commentListQuery from '../api/postCommentList.api';
  
const FeedDetailPage = () => {
  const { id } = useParams();
  const [post, setPost] = useState(null);
  const [commentsList, setCommentsList] = useState([]);
  const [inputComment, setInputComment] = useState('');

  const {data, isSuccess, mutate} = useMutation(commentListQuery(id, inputComment));
  const handlePostCommnets = async (event) => {
    event.preventDefault();
    mutate(id, inputComment);
    if(isSuccess){
      const newComment = data.data.comment;
    if (newComment) {
      // 새 댓글을 포함하도록 commentsList 상태를 업데이트
      setCommentsList((prevCommentsList) => [...prevCommentsList, newComment]);
      setInputComment('');
    }}
  };

  return (

    <PageTemplate>
      {/* 생략 */}
      {commentsList && (
        <CommentContaier>
          <ul>
            {commentsList.map((comment, idx) => (
              <Comment key={idx} comment={comment} />
            ))}
          </ul>
        </CommentContaier>
      )}

      {/* 댓글 작성 */}
      {post && (
        <CommentForm onSubmit={handlePostCommnets}>
          <CommentImage src={profileImage} alt="" />
          <ResizingTextarea
            rows="1"
            placeholder="댓글 입력하기..."
            onChange={handleCommentChange}
            value={inputComment}
          />
          <CommentBtn disabled={!inputComment}>게시</CommentBtn>
        </CommentForm>
      )}
    </PageTemplate>
  );
};

export default FeedDetailPage;

클릭 이벤트가 발생하면 다시 호출하기 위해서 mutate를 사용하였다. useMutation등 선언하려면 컴포넌트 바로 하위에 해야하기 때문이다. 성공하는 경우만 해놓았고, 보통 저렇게 쓰기 보다는 onSuccess를 사용한다고 하는데, 좀 더 알아봐야 겠다!!

결론

  • api를 호출하는 쿼리키를 만들자!
  • get요청만 useQuery 나머지는 useMutation을 사용한다.
  • 여러 상태에 대해 제공하기 때문에 이를 잘 사용하자!

Clone this wiki locally