Mojang / ore-ui

💎 Building blocks to construct game UIs using web tech.
https://react-facet.mojang.com/
MIT License
409 stars 18 forks source link

Calls to callbacks created via useFacetCallback can get outdated values #118

Open xaviervia opened 1 year ago

xaviervia commented 1 year ago

In a scenario where a function that is listening on a facet is calling another function created with useFacetCallback, the value of the same facet inside the second callback might be outdated.

For example:

const facet = createFacet({ initialValue: 'old value' })

function Comp() {
  // Since this is run on useLayoutEffect, it will
  // add the 
  const callback = useFacetCallback((value) => value, [], [facet])

  // Since this is run on render, it will add the
  // `.observe` subscription first
  useMemo(() => {
    facet.observe((value) => {
      console.log('here be new value: ', value)
      console.log('...and here is still old value: ', callback())
    })
  })

  return null
}

facet.set('new value')
xaviervia commented 1 year ago

The fix should probably be that useFacetCallback reads the facet values instead of listening to changes in them. It's unclear why we went with the first one.

xaviervia commented 1 year ago

Was actually fixed by https://github.com/Mojang/ore-ui/releases/tag/v0.4.4

This issue also exists in the useFacetRef BTW cc @pirelenito