Search code examples
reactjstypescriptredux-saga

Redux Saga continues loop if Page not Found


This is my rootSaga.ts

import { all } from 'redux-saga/effects';

import { Watcher } from '../sagas';

export default function* rootSaga() {
  yield all([Watcher()]);
}

my API axios

 import axios from 'axios';


const fetchAPI = () => {
  return axios.get('https://sample404Case');
};

export default fetchAPI;

this is my Saga

export function* Watcher() {
  yield takeLatest(actionIds.FETCH_SAMPLE_REQUEST_START, fetchSample);
}

function* fetchSample() {
  try {
    console.log('generated');
    const generatedSample = yield call(FetchSample);
    console.log(generatedSample);
    yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_SUCCESSFUL, payload: generatedSample.data });
  } catch (error) {
    console.log(error);
    yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_START, error });
  }
}

Note I deliberately want to have a 404 error but my problem is it makes a continues loop which makes my page to freeze.

Is there a way to stop the saga once there's an error once?


Solution

  • You are restarting the saga when you have an error which makes it go in an infinite loop (because you want it to error with a 404):

      catch (error) {
        console.log(error);
        yield put({ type: actionIds.FETCH_SAMPLE_REQUEST_START, error });
      }
    

    You should add another action for a failed state (e.g.: FETCH_SAMPLE_REQUEST_FAILED) and dispatch that inside the catch