F
F
flafy42018-08-11 17:27:49
JavaScript
flafy4, 2018-08-11 17:27:49

How to properly implement API calls in Vue.js?

How to properly implement API relationships in Vue.js?
Wrote a small API that saves data to the database. Hence, the code snippet from the user registration page component:

onNewUser () {
   const user= {
           id: null,
           login: this.login,
           email: this.email,
           password: this.pass,
   }
   this.$store.dispatch('createUser', user)
}

In the store, it adds a user to the state, but in the bus (vuex) you cannot use vur-resource, therefore you cannot contact the server from there, for example:
this.$http.post('http://test-api.com/methods/user/user.ad.php', {user: userPayload})

in file:
mutations: {
    createUser: function(state, userPayload) {
      state.products.push(product)
      // По логике тут нужно обращение к API что бы сохранить пользователя в БД, но vuex не позволяет это сделать.
    }
  },
  actions: {
    createUser: function({commit}, userPayload) {
      commit('createUser', userPayload)
    }
  },

And it is wrong to use such a construction in every component that needs some kind of API call. How to be?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Popov, 2018-08-11
@be_a_dancer

I recommend reading the official thread on this topic. Especially pay attention to the answers of the guy with the nickname jonagoldman

X
x-foby, 2018-08-12
@x-foby

A little off topic, but still for the future: it is better to implement API calls not in mutations, but in actions. Mutations should be used directly to change the state, the rest of the logic, especially related to asynchronous requests to the north, should not be written in them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question