2
votes

All:

I am pretty new to Redux, when I try to follow the tutorial about async action http://redux.js.org/docs/advanced/AsyncActions.html

There is a concept called thunk, I do not quite get the idea why we need a thunk to do async action, why we can not just simply dispatch init signal, then fetch data then dispatch finish signal in the promise from fetch data?

function fetchDataAction(dispatch){
    dispatch({
        type: "START"
    })
    fetch("DATA_URL")
        .then(function(res){return res.json();})
        .then(function(json){
            dispatch({
                type: "SUCCESS",
                data: json
            })
        })
}

Thanks

1
You pretty much described a thunk in your question. The fetching of the data happens asynchronously, thus a dispatch can only be triggered once we receive a response.Mario Tacke
@MarioTacke Thanks, so thunk is just a fancy word to do what I put here? And I do not need thunk at all if most my operation is simply fetch data?Kuan
thunks are more than a fancy word. It is my understanding that the way redux operates, all actions have to return an action which can be consumed by the reducer(s) immediately. Since the async action returns data at a later point (read: not immediately), we need to open an avenue to execute a specific action once we receive data. For this, lots of projects use redux-thunk middleware.Mario Tacke

1 Answers

1
votes

Redux store only recognize plain object as Action. Therefore you can only dispatch objects to the store. redux-thunk teaches the store to recognize function as Actions. For more info about redux-thunk, read from the author himself: How to dispatch a Redux action with a timeout?

The other way to think about it is that redux-thunk provide you ways to access dispatch directly so that you can dispatch whatever you want.

Without redux-thunk your action creators does not have dispatch as a parameter. In this case, fetchDataAction only works because redux-thunk give dispatch as a parameter to it.