0
votes

I am learning redux-thunk middleware as a beginner react developper, and I don't understand why dos the function (returned by redux-thunk) returns a promise (returned by fetch())

I tried not to return anything, and it worked, so why do we return it?

export function getCourses() {
  return fetch(baseUrl)
    .then(handleResponse)
    .catch(handleError);
}

export function loadCourses() {
  return function(dispatch) {
    dispatch(beginApiCall());// dispatch some synchronous action

    return courseApi
      .getCourses().then(courses => {
        dispatch(loadCourseSuccess(courses));
      }).catch(error => {throw error;});
  };
}  

For the component named MyComponent dispatching loadCourses() action

function MyComponent(props){
    .......
    useEffect(() => {
        loadCourses()
    });

    const mapDispatchToProps = {
        loadCourses,
        .....
    }
}
3
what exact function do you mean? loadCourses or that nested anonymous function(dispatch)?skyboyer
Here's a very good example showing that (returning Promises) in action: github.com/reduxjs/redux/issues/1676 (see the first comment).Mati

3 Answers

2
votes

I think i got the answer(from a colleague).

if you want to chain certain activities, your action would need to return a Promise.

it's just a good way to allow chaining activities after the result is returned!

1
votes

Well, first of all the function returns some data because you asked it to return some sort of result return function(dispatch) {...}. If you want to ignore the returned result just remove the return from return function(dispatch) {...}.

Secondly, the function returns a promise because of the way that you have written your call to API functions (wrapped inside promise and not returning callbacks upon function completion).

If you want to get the actual result of the API call you should use the Async / Await syntax.

-1
votes

With a plain basic Redux store, you can only do simple synchronous updates by dispatching an action. Middleware extends the store's abilities and let you write async logic that interacts with the store.

Thunks are the recommended middleware for basic Redux side effects logic, including complex synchronous logic that needs access to the store, and simple async logic like AJAX requests.https://github.com/gaearon/redux-thunk

The thunk middleware knows how to turn thunk async actions into actions, so you just have to have your simple_action() to be a thunk and the thunk middleware will do the job for you, if the middleware see a normal action, he will dispatch this action as normal action but if it's an async function it will turn your async action into normal action.

You can also see return promise from store after redux thunk dispatch