본문 바로가기
리액트

[리액트] React query parameter(=query string)으로 검색기능 구현하기

by 지 요니 2023. 6. 30.

검색기능을 구현하면서 서버에 query parameter로 검색 카테고리와 검색어를 함께 보내줘야하는 상황이 생겼다.

 

 

아래와 같이 검색 카테고리와 검색어를 함께 서버로 넘겨줘야했기 때문에 쿼리 파라미터를 이용하기로 했다.

먼저 검색 카테고리를 선택할 수 있게 selector를 이용해 option(카테고리)을 선택할 수 있게 하고

  const [currentOpt, setCurrentOpt] = useState("내용");
  const [option, setOption] = useState("contents");
  
  const optionChangeHandler = (currentOpt) => {
    if (currentOpt === "내용") {
      setOption("contents");
    } else if (currentOpt === "해시태그") {
      setOption("tag");
    } else if (currentOpt === "닉네임") {
      setOption("userNickName");
    }
  };
  const liClickHandler = (index) => {
    setCurrentOpt(optArr[index]);
    optionChangeHandler(optArr[index]);
    toggleCloseList();

검색버튼을 누르면 검색어와 검색 카테고리를 함께 전달해주었다.

const searchButtonClickHandler = useMemo(
    () =>
      debounce(() => {
        if (keyword.trim() === "") {
          setSearchResults([]);
          return;
        }
        const role = activeNavItem.toUpperCase();
        searchMutation.mutate({ keyword, option, role });
      }, 500),
    [keyword, activeNavItem, option, searchMutation]
  );

 

 

🟦 쿼리 파라미터(쿼리 스트링)

Query String(쿼리스트링)이란 url에 데이터를 전달하는데 사용되는 일반적인 방법 중 하나이다. 주로 요청하고자하는 URL에 부가적인 정보를 포함하고 싶을 때 사용한다. 

Query String 은 url 의 끝에 "?" 기호로 시작하고,

key=value 형식의 매개변수 쌍을 & 로 구분하여 나열한다.

/search?keyword?=서울&role=MODEL
위와 같은 URL에서 ? 뒤에 keyword?=서울&role=MODEL이 쿼리스트링이 된다.

 

쿼리 스트링을 이용하여 url에 검색관련 데이터를 전달하는 코드는 다음과 같다.

import { instance } from "../axios";

const searchFeedAxios = async ({ keyword, option, role }) => {
  try {
    const response = await instance.get(
      `/feeds/search?${option}=${keyword}&role=${role}`
    );
    return response;
  } catch (error) {
    throw error;
  }
};

export { searchFeedAxios };

댓글