D
D
Dmitry2019-10-11 17:23:25
React
Dmitry, 2019-10-11 17:23:25

How do you explain this magic?

Watch the video
What's the point...
When you click on add to cart, a request is made to the server to add an item to the cart.
For the duration of this request, the button must be blocked by the disabled
Button Code attribute:

<Button onClick={() => cart.add(product.id)} disabled={cart.inProcess(product.id)}>
  Add to cart
</Button>

Cart class:
@observable processId = {}

@computed get inProcess() {
  return (id) => {
    console.log(Object.keys(this.processId))
    return this.processId.hasOwnProperty(id)
  }
}

@action add(id) {
  this.processId[id] = true

  this.api.add(id).then(() => {
    this.products.push({id, count: 1})
    delete this.processId[id]
  })
}

If you remove console.log, then the getter stops working and the button is not blocked.
Why is this happening and how to fix it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2019-10-14
@dmitry-l

In Mobx, if no one accesses the observable field and it has never been used, then the getter for it works crookedly.
Since processIdit is already an object and it is very easy to access it, there is no need to use a getter. Instead of
enough to write:
and everything will work.

A
Alexey Nikolaev, 2019-10-11
@Heian

Apparently you have mobx? In console.log you have access to the `processId` variable itself, while the rest of the time you only need to check if the id property is there. Write a function like this and I'm sure everything will work.

@computed get inProcess() {
  return (id) => {
    const processIds = this.processId;
    return processIds.hasOwnProperty(id)
  }
}

And here's why - very interesting)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question