Using Redux-Thunk middleware to dispatch actions which fetch data from an external API

Dear campers,

I am relatively new to Redux. I am using Redux-Thunk middleware to dispatch actions. One of my action creators makes a call to an external API and i am using the response data to dispatch another API call from a different action creator. Below, i am using fetchQuizTotal to dispatch a call to an external API from fetchTriviaCategories because it needs the data returned from fetchTriviaCategories API call to make its own API call. It works but i am a bit hesitant because i am not sure if this is a good practice. Is there a better way of achieving the same result?

const fetchQuizTotal = (categoryId) => {
    return (dispatch) => {
      return fetch(baseUrl + categoryId)
        .then((response) => response.json())
        .then((quizCount) => {
          dispatch(quizCount);
          return quizCount;
        });
    };
  };


const fetchTriviaCategories = () => {
  return (dispatch) => {
    return fetch(triviaCategoriesUrl)
      .then((response) => response.json())
      .then((triviaCategories) => {
        const { trivia_categories } = triviaCategories;
        dispatch(fetchQuizTotal(+trivia_categories[0].id));
        return trivia_categories;
      });
  };
};

Hey there,

so without the whole code, it’s hard to guess,
but in general it is good advice to decouple stuff and reduce complexity.

E.g. when you fetch quizContent, is it necessary to fetch this from the API or can you calculate it with existing data you already got?

I can’t calculate quizCount from the fetched trivia_categories. I need trivia_categories to access the unique id of the categories and then use the unique id of a trivia_category to fetch its total quizCount in the database. I am using the data returned from the first call to the API to fetch the second data.

Yeah, I mean quizCount sounds like a number of quiz questions or something like that.
So don’t you fetch these quiz questions before these calls, so that you can calculate this quizCount from existing data?

Yes quizCount is the total quiz. The API only returns 50 quiz per request not all of them in the database. I am interested in the total quiz count. You can retrieve the total quiz count by making a separate API call if you are interested.