1
votes

I am trying to learn a react-redux. And in order to call the external rest API, I am using thunk middleware.

However the syntax to so confuses me a lot, I would appreciate if someone can explain me.

export function listTodos() {
  return (dispatch) => axios.get("http://localhost:5001/todos")
    .then(response => {
      console.log(response.data);
      dispatch(getTodos(response.data));
    })
}

export function _listTodos(todos) {
  return {
    type: 'LIST_TODOS',
    todos: todos
  }
}

so in order to get the response from the external API, I am calling listTodos function, which dispatches an action returned by listTodos function.

The part confuses me is Syntax (maybe because it's ES6 an I am not very familiar with that).

how come return is taking a parameter, dispatch?

from where this dispatch is coming, I am not passing anything when I call listTodos

why do I even need a return, shouldn't dispatching an action enough from within then

1
No, you're returning an arrow function that takes a parameter. dispatch is passed in by the middleware. No, it is not enough because you need to have the dispatch argument in scope which is only passable via a wrapped arrow function (which is callable by the middlware) - Andrew Li
so return (dispatch) => is actually return function (dispatch) { correct? - Gaurang Shah
Correct, you're just returning another function (that is an arrow function) - Andrew Li

1 Answers

0
votes

Redux only accepts plain javascript objects for dispatch. The thunk middleware overcomes this by allowing you to provide functions to the dispatch. In this example, essentially what you're doing is returning a function reference to the dispatch which will be executed by thunk.

how come return is taking a parameter, dispatch?

from where this dispatch is coming, I am not passing anything when I call listTodos

Once thunk encounters a function it executes that function and passes dispatch as a parameter so that you can use it in the function to actually do the dispatch (_listTodos(todos)). So thunk will do something like this

   if(typeof action === 'function') {
       //Reason why it takes a dispatch parameter
       //And thunk is the one who sends it to the function
       action(dispatch);
   }

where action is the function that you have returned from your listTodos()

why do I even need a return, shouldn't dispatching an action enough from within then

return is needed to give thunk the function so that it can perform the above action.