9

I am new to ES6 and advanced javascript. I have seen examples of code using the axios http client like this:

axios.xxx(...).then((res) => dispatch(success(res)) , (err)=> dispatch(error(err)))

whereas I am doing:

axios.xxx(...).then(function(res){...}).catch(function(err){...});

I tried to look up dispatch on MDN but only found DispatchEvent... which is not the same? I ask because although my code works, I am finding http error codes like 403 etc from my api are handled as errors by axios, while i would prefer to handle them myself in the app. (Update: when I added the dispatch tag to this question, I saw a brief summary of the meaning but I am still confused).

What is the reason or advantage for using dispatch? Is "dispatch()" part of axios, or ES6, or nodejs? thx.

yen
  • 1,769
  • 2
  • 15
  • 43

1 Answers1

9

When I see dispatch I immediately think of redux-thunk (a popular middleware for Redux). It is a good example of why passing dispatch is useful. Basically dispatch is used as a callback which gets invoked once some async action is complete. In redux-thunk dispatch is simply a function which dispatches an action to the Redux store after, let's say, you fetch data from an API (which is asynchronous). You can pass any function you like to .then() or .catch() of some Promise and it will be invoked upon success or failure.

Alexander Vitanov
  • 4,074
  • 2
  • 19
  • 22
  • thank you for this info... but i think it doesn't really answers the question. – yen Oct 29 '17 at 23:00
  • What do you need to know exactly? – Alexander Vitanov Oct 29 '17 at 23:01
  • 1
    per my question itself: **(1) Is "dispatch()" part of axios, or ES6, or nodejs?** and **(2) why would you use dispatch instead of .then() and .catch()**? – yen Oct 29 '17 at 23:03
  • As I said, dispatch is probably a function provided by a library. Can you tell us where you saw it? – Alexander Vitanov Oct 29 '17 at 23:05
  • 2
    Oh I see... I saw references to dispatch when I was trying to debug my code which uses axios... and then several browser tabs later, I ended up here: https://twitter.com/dan_abramov/status/770914221638942720?lang=en ... I've lost the trail of how I got there. So I guess this is specific to redux and I don't need to worry about this if I'm not using redux? I'm only using plain react. – yen Oct 29 '17 at 23:14
  • Absolutely, just carry on :) – Alexander Vitanov Oct 29 '17 at 23:26