Search code examples
javascriptvue.jsvuexdeferred

How to change jquery Deferred to use Vue nexttick?


I need to change this as I have read nextTick is a better option compared to deferred.

This is the original code that works well:

methods: {
    ...mapActions(['fetchOverdraftLogs', 'setOverdraftFilters', 'fetchUserEventsCsvFile']),
},
  computed: {
    ...mapGetters(['getOverdraftLogs'])
  },
...
        loadData: filters => {
          const d = $.Deferred()
          this.fetchOverdraftLogs({ params: this.filtersToSend(filters) })
            .then(res => {
              d.resolve(this.getOverdraftLogs)
              this.setFilterValues()
            })
          return d.promise()
        })
        }

However, I am not able to rework this with nextTick:

loadData: filters => {
  this.fetchOverdraftLogs({ params: this.filtersToSend(filters) })
  this.$nextTick(() => {
    this.setFilterValues()
    this.getOverdraftLogs
  })
}

I need to make sure for the grid that after the API is called it reads the data from the state.

Could you assist?


Solution

  • Deferred pattern is generally an antipattern, especially with ES promises. It's not an alternative to nextTick. Promises are already asynchronous, a promise that is instantly resolved provides a small delay. nextTick provides a delay that is big enough DOM to be updated.

    nextTick supports promises but here it's not needed.

    It should be:

        loadData: filters => {
          return this.fetchOverdraftLogs({ params: this.filtersToSend(filters) })
            .then(() => {
              this.setFilterValues()
              return this.getOverdraftLogs;
            })
        }
    

    Vuex actions aren't supposed to return data they operate on, so there should be no res.