mangocaptain mangocaptain - 3 months ago 21
React JSX Question

React redux multiple requests in one action creator

I want to make 2 request in a row, kinda in a waterfall fashion. I want to first request a specific pokemon, and then based on the returned obj's payload's type, I want to request more information. I thought it would be best to separate this out to several action creators but feel weird that

fetchPokemon
ends with another fetch. Is this best practice?

export const fetchPokemon = function (pokemonName) {
return function (dispatch) {
dispatch(requestPokemon(pokemonName))
const requestURL = `http://pokeapi.co/api/v2/pokemon/${pokemonName}/`
return $.ajax({
url: requestURL,
}).done(function (data) {
dispatch(receivePokemon(data))
fetchPokeTypeInfo(data.types[0].type.url)
})
}
}

...

export const fetchPokemonTypeInfo = function (url) {
return function (dispatch) {
dispatch(requestPokemonTypeInfo(url))
return $.ajax({
url: url,
}).done(function (data) {
dispatch(receivePokemonTypeInfo(data))
})
}
}

Answer

I don't think there's anything particularly wrong with breaking these two up. One question I'd ask is: "Would I ever call fetchPokemonTypeInfo() directly, not from fetchPokemon()?". If not, then I'd just return the second .ajax call from the .done() function in the first. If the first call is always a dep, it seems easier to reason about what is happening if they just nest. Also, if you do want to keep them separate you'll need to pass the dispatch function as well as the url to the second function, otherwise dispatch is undefined in fetchPokemonTypeInfo().

Update:

You could nest the second call in the first like this:

export const fetchPokemon = function (pokemonName) {
    return function (dispatch) {
        dispatch(requestPokemon(pokemonName));
        const requestURL = `http://pokeapi.co/api/v2/pokemon/${pokemonName}/`;
        return $.ajax({
            url: requestURL,
        }).done(function (data) {
            dispatch(receivePokemon(data));
            dispatch(requestPokemonTypeInfo(data.types[0].type.url));

            return $.ajax({
                url: data.types[0].type.url,
            }).done(function (data) {
                dispatch(receivePokemonTypeInfo(data));
            });
        });
    }
}