NullVoxPopuli / ember-resources

An implementation of Resources. Supports ember 3.28+
https://github.com/NullVoxPopuli/ember-resources/blob/main/docs/docs/README.md
MIT License
91 stars 37 forks source link

second run of `trackedFunction` seems to first re-render with old value before loading new value #1010

Closed Techn1x closed 1 year ago

Techn1x commented 1 year ago

I've been playing around with trackedFunction and it works great but I have noticed some odd behaviour.

I have a trackedFunction like this;

// bookId is an arg, passed in to this component by a tracked QP from a controller

fetchBook = trackedFunction(this, () => {
  return this.store.findRecord('book', this.args.bookId, { reload: true })
})

and a template like this;

{{log "ISPENDING:" this.fetchBook.isPending}}
{{#if this.fetchBook.isPending}}
  LOADING
{{else if this.fetchBook.value}}
  {{log "RENDERED WITH ID" this.fetchBook.value.id}}
{{/if}}

On initial load with bookId 33, I get the output

ISPENDING: true
ISPENDING: true
Mirage: [200] GET http://127.0.0.1:4017/api/v1/books/33
ISPENDING: false
RENDERED WITH ID: 33

So far so good, but when the QP changes (say, to bookId 27), I get this output;

ISPENDING: false
RENDERED WITH ID: 33
ISPENDING: true
mirage-esm.js:6707 Mirage: [200] GET http://127.0.0.1:4017/api/v1/books/27
ISPENDING: false
RENDERED WITH ID: 27

It seems to re-render with the old state & value before flipping into isPending. Is this expected behaviour? ~Is it specific to ember-data? (running 4.12.3)~ EDIT: further testing has shown this occurs for other async requests as well, not just ember-data.

Techn1x commented 1 year ago

The motivation here is I have other tracked functions down the line in child components that use data from the book record to then go and request further book metadata records.

So when it re-renders with the old book (instead of going to isPending), it goes and triggers the child component's tracked functions for the old metadata requests again.

(I've made sure to exclude this as the cause from my testing though by completely removing the child component)

Techn1x commented 1 year ago

@NullVoxPopuli do you know if this is expected behaviour or a bug?

Or is this more of an issue with the underlying ember-async-data library? I can file there instead if you like https://github.com/tracked-tools/ember-async-data

NullVoxPopuli commented 1 year ago

Sorry i forgot to look at this! There's for the ping! I'll investigate tomorrow

NullVoxPopuli commented 1 year ago

Found it was an issue with how trackedFunction is managing state -- fix here: https://github.com/NullVoxPopuli/ember-resources/pull/1011/files#r1346291970