cklmercer / vue-stash

Easily share reactive data between your Vue components.
MIT License
403 stars 29 forks source link

Promises for remote API #23

Closed zatziky closed 7 years ago

zatziky commented 7 years ago

Hi there,

great library you are maintaining for us. I appreciate how simple it is. With all this simplicity do you think some promise handling would fit in?

Imagine I have 2 components: Root, Child.

In Root.vue, I fetch item and assign it to the store upon app init:

store: {
  item: 'path.to.item' 
}

mounted() {
    itemService
       .get(itemId)
       .then(item => {
            this.item = item
       })
}

In Child.vue, I want to use item but it hasn't been fetched yet.

store: {
  item: 'path.to.item' 
}

mounted() {
    const itemKey = this.item.key // this.item is undefined
}

Is there some strategy how to handle it without modifying vue-stash? Or does need some promise support to handle this case?

cklmercer commented 7 years ago

This is an interesting challenge.. One possible solution, albeit not so elegant, might be..

store.js

{
  item: null,
  itemSet: false
}

root.vue

mounted() {
  itemService.
    .get(itemId)
    .then((item) => {
      this.item = item
      this.itemSet = true
    })
}

child.vue

computed: {
  itemKey() {
    return this.itemSet ? this.item.key : null
  }
},

watch: {
  itemKey(newValue, oldValue) {
    if (oldValue === null) {
      // item was just set
    }

    // item was updated
  }
}

The above snippet isn't exactly elegant, but I believe it'd work. I'm definitely open to alternative solutions and am intrigued by the problem itself. I don't however have a better idea off the top of my head.. I'll be sure to keep this challenge simmering in the back of my mind, hopefully something will come up.

Any ideas of your own?

zatziky commented 7 years ago

@cklmercer Why not, it's a way too. Unfortunately, this way won't help if you for example need to subscribe to a particular destination in STOMP - the destionation string would just contain undefined.

I will use the same way like you. If my intuition finds out how to solve it I'll come back and post it.

cklmercer commented 7 years ago

Feel free to reopen this issue if you come up with a solution. I'll be sure and reference it if I do.