warCommander
warCommander

Reputation: 449

useEffect keep rendering workaround

I have a small problem. I want to call 4 APIs when the component start rendering so I used use effect for that so I loop my array which has 4 items and at each item I call an API, and each API save the result in selector called filtersCount. The problem is when filtersCount updated the loop start over. How I can prevent this without disabling the eslint ??

const fetchCounts = useCallback(
  (item) => {
    if (!filtersCount[item.key]) {
      dispatch(getFilterCount({ filters: item.countFilters, key: item.key }));
    }
  },
  [dispatch, filtersCount]
);

useEffect(() => {
  exploreItemTypes.map((item) => {
    fetchCounts(item);
  });
}, [exploreItemTypes, fetchCounts]);

Upvotes: 1

Views: 60

Answers (2)

Zack_Az
Zack_Az

Reputation: 36

I think the simplest way is to use an empty array in your useEffect.

useEffect(() => {
    exploreItemTypes.map((item) => {
      fetchCounts(item);
    });
  }, []);

this will stop once your iteration is over.

Upvotes: 0

سعيد
سعيد

Reputation: 1764

you can use a Ref for this :

const firstRender =useRef(false)
useEffect(() => {
    if(firstRender.current == false){
      exploreItemTypes.map((item) => {
        fetchCounts(item);
       });
      firstRender.current = true 
    }

  }, [exploreItemTypes, fetchCounts]);

Upvotes: 1

Related Questions