김우희·2022년 6월 16일

상황

=> selectbox의 데이터를 서버에서 불러와서 보여주려고 하는데 선택된 값이 변경 될 때마다 custom hook을 계속 불러옴
custom hook을 한번만 불러올 수 있는 방법이 없을까 ?


  1. select박스의 하위 메뉴를 서버에서 가져와서 보여줘야함
  2. custom hook 을 만들어서 아래와 같이 데이터를 한번에 불러오고자 함 => useQuery를 활용해서 데이터를 한번에 불러오고 싶음 but 각각 데이터를 불러오는 api는 다르다!!

  1. 페이지 별로 selectbox의 데이터가 달라지기 때문에 useQuery의 enabled를 통해 페이지에서 필요하지 않은 데이터면 부르지 않음
const useGetAllLeagueData = (menu) => {
    const [data, setData] = useState(null);
    const searchList = SEARCH_SELECT[menu];

    const {
        isLoading: teamLoading,
        isFetching: teamFetching,
        data: teamList
    } = useQuery('teamList', () => getData('/club'), { enabled: searchList.includes('team') });
    const {
        isLoading: roundLoading,
        isFetching: roundFetching,
        data: roundList
    } = useQuery('roundList', () => getData('/round'), {
        enabled: searchList.includes('round')
    });
    const {
        isLoading: playerLoading,
        isFetching: playerFetching,
        data: playerList
    } = useQuery('playerList', () => getData('/player'), {
        enabled: searchList.includes('player')
    });

    console.log(teamList, roundList, playerList);

    useEffect(() => {
        setData({ round, team, player });
    }, []);

    return {
        data,
        isLoading: teamLoading || roundLoading || playerLoading,
        isFetching: teamFetching || roundFetching || playerFetching
    };
};

export default useGetAllLeagueData;
  1. 해당 selectbox가 필요한 페이지에서 위에 만든 커스텀 훅을 불러와서 selectbox에 데이터를 보내줌
    const { data: dynamicSelectData } = useGetAllLeagueData('MatchInfo');

return  <Search
                isLoading={isLoading}
                isFetching={!!(!isLoading && isFetching)}
                total={dataList?.count}
                dynamicSelectData={dynamicSelectData || {}}
            />

문제점

selectbox에서 메뉴를 변경할때 마다 custom hook을 호출함

딱 한번만 호출하고 싶은데 페이지에서의 state값이 변경 될 때마다 자동으로 custom hook을 부름 ㅠㅠ

useEffect안으로 넣을 수도 없고...
컴포넌트 밖으로 뺄 수도 없고..

딱 한번만 부르려면 어떻게 해야하징??

profile
프론트엔드 개발자

0개의 댓글