Search code examples
reactjsredux-saga

Getting infinite API Call when using Dispatch in useEffect (Redux Saga)


I am trying to fetch data from API and store it in a state using Redux Saga. But action is getting dispatched infinite time while the result is not being returned by the API. I can see the API call in the network tab and it is showing 200 with the actual response.

API.js

export const fetchStatsAPI = (startDate, endDate, isMonthly = false) => (
  axios.get('apicall')
);

Action.js

export const fetchIssues = ({ startDate, endDate, isMonthly }) => ({
  type: types.FETCH_STATS,
  startDate,
  endDate,
  isMonthly,
});

Reducer.js

 export default function Reducer(state = initialState, action) {
  switch (action.type) {
    case types.FETCH_STATS:
      console.log("Action called");
      return {
        ...state,
        Stats: action.payload,
      };
    default:
      return state;
  }
}

Saga.js

function* handlePriorityIssuesSaga(params) {
  try {
    const response = yield call(Api.fetchStatsAPI, params.startDate, params.endDate, params.isMonthly);
    yield put(actions.fetchIssues(response.data));
  } catch (e) {
  }
}

index. js

export default function Issues({ startDate, endDate, isMonthly }) {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(actions.fetchIssues({ startDate, endDate, isMonthly }));
  }, [startDate, endDate, isMonthly]);

  const { IssuesStats } = useSelector((state) => state.dashboard);

  return (
    <p>hello</p>
  );
}

Solution

  • You are using the same action creator actions.fetchIssues for initiating the fetch and dispatching the results of the fetch.

    In your component:

    dispatch(actions.fetchIssues({ startDate, endDate, isMonthly }));
    

    In your saga:

    yield put(actions.fetchIssues(response.data));
    

    In some piece of your code which isn't included in your question, there is a saga watcher that is looking to take a fetch issues action and pass it to your handlePriorityIssuesSaga function. The action that you dispatch via put in handlePriorityIssuesSaga is going to trigger that same matching condition such that this function triggers itself infinitely.

    You need two separate actions for initiating the fetch and storing the results, the same as in this answer.