obi patrick
obi patrick

Reputation: 73

Dispatch receiving undefined as a value

I have issue updating the state after a dispatch.

Console logging the result of the dispatch shows Promise pending and value undefined hence, never gets to the store.

console result

Below is the function that calls the dispatch handler.

unsetSelected() {
   let some = this.$store.dispatch('user/selectedDevice', null)
   console.log(some)
}


<span class="ellipsis" @click="setSelected(device)">
     <i v-if="selectedDevice && selectedDevice.id == device.id"
        @click="unsetSelected()"
        class="fa fa-times-circle">
     </i>
     <i v-else="" class="fa fa-ellipsis-v"></i>
</span>

This is the action handler:

selectedDevice ({ commit }, data) {
    commit ('SELECTED_DEVICE', data);
}

Upvotes: 2

Views: 1670

Answers (2)

obi patrick
obi patrick

Reputation: 73

I put alert on the mutation handler and discovered that the code was working as expected only that it was also firing the dispatch function above in the DOM.

I have to chain it with .stop modifier: @click.stop="unsetSelected()"

Upvotes: 1

aBiscuit
aBiscuit

Reputation: 4732

From Vuex API reference for dispatch instance methods:

Returns a Promise that resolves all triggered action handlers.

So calling dispatch returns a Promise. In order to receive data inside component, this promise should be resolved.

You can modify component's method to following:

// using async/await
async unsetSelected() {
  try {
    let some = await this.$store.dispatch('user/selectedDevice', null)
    console.log(some)
  } catch (error) {
    // handle error
  }
}

// using Promise API
unsetSelected() {
  this.$store.dispatch('user/selectedDevice', null)
    .then((some) => {
      console.log(some)
    })
    .catch((error) => {
      // handle error
    })
}

Also, selectedDevice does not return any data, so some (or response) from resolved promise will be undefined for example code provided in question.

To fix that, store action should have a return statement with desired data to return to the component.

Though, following Vuex architecture, it would be suggested to map state/getters, whose values will be reactively updated after state mutation has been committed.

Upvotes: 0

Related Questions