Andrew Kim
Andrew Kim

Reputation: 3335

defer destroyed in vue lifecycle hook

In my component I have a mounted hook that fetches some data as an async request:

mounted() {
  this.fetchData()
}

and on beforeDestroy I delete the data from the store:

beforeDestroy(){
  this.destroyDataInStore()
}

These work fine so long as the request in mounted resolves prior to the component begins its tear down.

Is there any way I can defer the beforeDestroy until after the promise has resolved in the mount?

Upvotes: 2

Views: 1684

Answers (1)

Hammerbot
Hammerbot

Reputation: 16344

You could store the promise:

export default {
    data () {
        return {
            thePromise: null
        }
    },
    mounted () {
        this.thePromise = this.fetchData()
    },
    beforeDestroy () {
        this.thePromise.then(() => {
            this.destroyDataInStore()
        })
    }
}

But in order to be sure that everything works fine I would use the created hook instead of the mounted one:

export default {
    data () {
        return {
            thePromise: null
        }
    },
    created () {
        this.thePromise = this.fetchData()
    },
    beforeDestroy () {
        this.thePromise.then(() => {
            this.destroyDataInStore()
        })
    }
}

Upvotes: 2

Related Questions