L
L
laguna11322018-03-02 19:51:58
JavaScript
laguna1132, 2018-03-02 19:51:58

What is Redux-thunk for?

What is redux-thunk for if you can work like this:

import {START, SUCCESS, FAIL} from '../constants'

export default store => next => action => {
    const {callAPI, type, ...rest} = action
    if (!callAPI) return next(action)

    next({ 
        ...rest, type: type + START
    })
        fetch(callAPI)
            .then(res => res.json())
            .then(response => next({...rest, type: type + SUCCESS, response}))
            .catch(error => next({...rest, type: type + FAIL, error}))
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Gamega, 2018-03-02
@laguna1132

to be honest, a strange question - the task is trivial, but in order not to scare off the masses, a well-tested solution was written, which is enough for a lot of cases

function createThunkMiddleware(extraArgument) {
  return ({ dispatch, getState }) => next => action => {
    if (typeof action === 'function') {
      return action(dispatch, getState, extraArgument);
    }

    return next(action);
  };
}

const thunk = createThunkMiddleware();
thunk.withExtraArgument = createThunkMiddleware;

export default thunk;

for those who do not like to climb the github sources, the code above is all redyx-thunk code + there are also tests that are somewhat longer)
there is no special magic, I will not say that your example is better, but if you like it, then use it, but be prepared to answer the question colleagues, why didn’t thunk or saga take it? everyone is interested in him, but what is the profit of your decision?
these questions are not specific to your code, but in general - quite justified questions when someone drags their bike into the project instead of a well-known solution

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question