L
L
lleballex2020-08-08 08:25:14
JavaScript
lleballex, 2020-08-08 08:25:14

Why are mutations called at the very end in Vue.JS?

I have a Vue.JS project . In App.vue , when I create it, I make a request to the server with the API, after which I receive user data ( checkAuthToken ). Then in another object, when creating, I also send a request to the server, but I already use the user ID that comes in the first request ( getUser ).
I make queries like this:

axios.get('...', {...}).then(response => {commit('setUserInfo', response.data ...)}).catch(...)
. In then , I put the user data through mutations. Everything seems to be working. But there is a problem. First, checkAuthToken is called , then getUser , and only then mutations that set the user's data (including the ID). Why are they called at the very end and not at the beginning, and how can I fix this?
And yet, I think it's all related to await .

In app.vue :
async created() {
  var result = await this.$store.dispatch('checkAuthToken', {
    token: auth_token
  })
  ...
}

In another vue :
async created() {
  var result = await this.$store.dispatch('getUser', {
    id: this.$store.getters.userId     // мутации, которые ставят айди еще не вызывались, возникает ошибка
  })
  ...
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2020-08-08
@lleballex

Well, imagine: you are sitting at home, you decide to gobble up pizza. So what needs to be done - order a pizza, wait for the courier to bring it. Well, as soon as he brings it, you can eat it. And you ask: why can you start eating pizza only after it is brought? How to fix this, how to start eating pizza immediately after ordering? Yes, damn it, you will sit and wait, sit and wait, sit and wait.
You can sit and wait in different ways:
Option once - do not instantiate a component that requires a user id to work correctly until it is received:

<компонент-которому-нужен-id-пользователя v-if="$store.getters.userId">

Option two is to keep track of the user id, and perform actions that require it only when it exists:
watch: {
  '$store.getters.userId': {
    immediate: true,
    handler(userId) {
      if (userId) {
        ...
      }
    },
  },
},

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question