React 디펜던시 무한 API 호출

김용희·2022년 3월 30일
0
  const __GetWineState = useCallback(() => {
    return axios({
      method: "GET",
      url: process.env.BACK_EC2 + "wine",
      // url: "http://j6a101.p.ssafy.io:8080/api/wine",
    })
      .then((res) => {
        console.log(res);
        setWines(res.data.object);
        return res.data;
      })
      .catch((err) => {
        return err;
      });
  }, []);

  useEffect(() => {
    __GetWineState();
    dispatch(feedAction.getFeed());
  }, [__GetWineState, dispatch]);

get요청한 API 무한호출할 때
디펜던시를 잘못 건 경우가 많다.
그럴경우 처음 get 호출한 API의 res.data를 useState에 setWines해서 그 wines변수를
하위 컴포넌트에서 사용하다가
특정 필터 조건이 적용됬을때
다시 리렌더 되서 무한 호출되는 경우가 있는데

이경우 첫 get 호출한 API의 res.data를 useState로 setWines 하고
그리고 dispatch(feedAction.getFeed()); 로 res.data를 리덕스에도 저장한다

  const feedstate = useSelector((state: RootState) => state.feed.items);
  const applyFilters = useCallback(() => {
    let updatedList = feedstate;
    console.log(updatedList);

    // Rating Filter
     if (selectedRating) {
      updatedList = updatedList.filter(
        (item: any) =>
          item.ratingAvg >= parseFloat(selectedRating) &&
          item.ratingAvg <= parseFloat(selectedRating) + Number(0.6)
      );
    }
    ...~~
  }

여기서 3번째줄에 feedstate 를 필터 리렌더가 일어났을때 초기값으로 설정해줘야한다
만약 feedstate가 아니라 res.data로 저장한 ustState의 wines 를 직접 받아오면
필터되고 다시 applyFilters 함수가 실행됬을때
이미 해당 wines가 줄어들어서 다시 가격값을 상승시킬때나 다른 카테고리를 클릭했을때
그 줄어든 상태값에서 다시 필터가되서 처음 데이터 기준 필터가 되는것이아니라
필터된 데이터에서 다시 필터되는 상황이 온다 .
그러므로 초기 전체 호출된 온전한 값을 리덕스에 넣고
다시 applyFilters가 실행됬을 때 다시 리덕스의 온전한 값을 받아와서
새로운 updatedList 로 필터를 해줘야한다.
useState는 값이 변형되고 redux의 저장된 값은 다시 dispatch를 하지 않는 이상 변형되지 않는다.

profile
He threw his knapsack over the brick wall

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN