0

I have a code which works perfectly fine but I have a question inside my head!

Is that code well written?

I am not that good with JavaScript but I start to learning few months ago and I am also studying good practices to keep my code clean and organised!

There is the code

export const getSources = ({ dispatch }, data) => {
  return Api.getSources(data)
    .then((response) => {
      dispatch(types.GET_SOURCES, response.data);
      return response;
    })
    .catch((response) => window.console.log('Could not get Sources List!'));
};

That is a actions from my Vuex and what really bothers me is the double return! That was the only option that I've found to get the response at my component!

Somebody can do it better and tells me how?

The method from my component where calls this action

fetchRecordList() {
  this.getSources().then((response) => {
    window.console.log(response);
  });
},

Thanks in advance!

Gustavo Bissolli
  • 1,551
  • 3
  • 22
  • 36
  • 1
    The code if fine from a technical point of view. But what do you need the response in the component for? To to vuex "correctly", you would not use that result directly in the component. You would rely on the vuex getter method reactively updating your data. – Linus Borg Apr 12 '16 at 15:22
  • ..also, the to returns are fine. You will be using `return` a lot when using Promises like you do here. That's simply how it works. – Linus Borg Apr 12 '16 at 16:04
  • Understand @LinusBorg! I need to get an answer at my component in case there is any validation error to show then on the form! About storing the response on the vuex getter crossed my mind but I thought it is not a good idea because it is a information that matter only to specific component and not to the entire app! What do you think? – Gustavo Bissolli Apr 12 '16 at 16:31
  • Generally, doing it the "vue way", the validation error should also be saved in the state of vuex, received via a getter and through that, be displayed in the form accordingly. Other parts of your app might also need to know weither the validation failed. For example, you might think tomorrow to extract the display into a notification component. Example: http://vuex.vuejs.org/en/actions.html (3rd code block on that page) – Linus Borg Apr 12 '16 at 16:45
  • Uh man I got it!! You're right! I am gonna change it right now!! Thanks for the help!! Would you like to post it as an answer to check it as correct or can I do it for you? – Gustavo Bissolli Apr 12 '16 at 16:50
  • feel free to do that yourself, preferably with the actual solution you implement. – Linus Borg Apr 12 '16 at 16:54
  • Cool!! I am going to implement it and then I will add an answer here... thanks man! – Gustavo Bissolli Apr 12 '16 at 17:01

0 Answers0