score:0

a different solution is to use the redux-saga middleware. this lets you write something like this:

function* loadchefssaga() {
    # takelatest sets up a system that spawns the inner generator every time
    # an action matching the pattern is dispatched. if the inner generator
    # is still running when additional actions are dispatched, it is cancelled,
    # and a new one is spawned.
    yield takelatest('recipe_selected', function* (recipe) {
        # when a promise is yielded, the generator is resumed when the promise
        # resolves. alternatively, if it rejects, the rejected value is thrown
        # into this generator.
        const {chefs} = yield loadchefs(recipe)

        # assuming chefsloaded is an action creator for chefs_loaded
        # `put` is redux-saga's equivelent of `dispatch`. we use it because
        # the saga doesn't have direct access to the `dispatch` function.
        yield put(chefsloaded(chefs))
    })
}

i'm assuming that you have a basic familiarity with how javascript generators work. if not, go look them up; they're a powerful pattern. in this case, redux-saga uses them to construct functions that can block on things. every time something is yielded, redux-saga treats it as an "effect" that it knows how to process. for instance, when a promise is yielded, redux-saga sets it up so that the generator is resumed when the promise resolves (or something is thrown into the generator if it rejects).

score:4

are you familiar with redux-thunk? https://github.com/gaearon/redux-thunk

with redux-thunk applied as middleware, you can do something like this:

function selectrecipe(recipe) {
    return function (dispatch) {
        dispatch(setrecipe(recipe));
        return loadchefs(recipe).then((res) =>
            dispatch(setchefs(res.chefs))
        );
    };
}

where setrecipe and setchefs are simple action creators. e.g.

function setrecipe(recipe) {
    return {
        type: set_recipe,
        recipe
    };
}

function setchefs(chefs) {
    return {
        type: set_chefs,
        chefs
    };
}

i recommend reading the docs on async actions. https://redux.js.org/advanced/async-actions


Related Query

More Query from same tag