Search code examples
javascriptreactjsredux-saga

Dollar sign identifier in redux sagadollar sign identifier in redux saga


I want to send a paginated get request in the saga with Axios get but in the first approach it returns undefined and in the second one it works. in the first one, I used a dollar sign identifier in the URL. what is happening under the hood

first:

function* workGetAllCats(action: any): any {
  let pageNumber = action.payload;

  let URL = `/api/admin/category?page=${pageNumber }`;

  const fetchAllCats = yield call(() => axios.get(URL));
  const formattedResponse = fetchAllCats.data;
  yield put(getAllCatsSuccess(formattedResponse));
}

function* catIndexSaga() {
  yield takeEvery("catIndex/getAllCats", workGetAllCats);
}
export default catIndexSaga;

second:

  function* workGetAllCats(action: any): any {
  let pageNumber = action.payload;


  const fetchAllCats = yield call(() =>
    axios.get(`/api/admin/category?page=${pageNumber}`)
  );
  const formattedResponse = fetchAllCats.data;
  yield put(getAllCatsSuccess(formattedResponse));
}

function* catIndexSaga() {
  yield takeEvery("catIndex/getAllCats", workGetAllCats);
}
export default catIndexSaga;

I want to know what is happening and what is the difference between the first and second approaches


Solution

  • First approach:

    Once you get to.

      const fetchAllCats = yield call(() => axios.get(URL));
    

    URL is already defined as undefined. as JavaScript doesn't go backward :D

    The second approach, however, you are building the URL the moment you want to make the call as well.

    Since pageNumber refers to action. payload, meaning it's referring by the source to the parameter, as the second call, pageNumber will be defined. And you are calling it and you are also making the URL

    So you will be getting a new pageNumber

    The first approach is incorrect. The second approach could be better if:

    function* workGetAllCats(action: { payload: number }): any {
      const fetchAllCats = yield call(() => {
        let newURL = `/api/admin/category${action.payload ? `?page=${action.payload}}` : ''}`    
        axios.get(newURL)
      });
      const formattedResponse = fetchAllCats.data;
      yield put(getAllCatsSuccess(formattedResponse));
    }
    
    function* catIndexSaga() {
      yield takeEvery("catIndex/getAllCats", workGetAllCats);
    }
    export default catIndexSaga;
    

    Good Luck Bro :)