mobxjs / mobx-react

React bindings for MobX
https://mobx.js.org/react-integration.html
MIT License
4.85k stars 349 forks source link

UI not reacting to observable changes #865

Closed dart200 closed 4 years ago

dart200 commented 4 years ago

Intended outcome

I'm trying to create reactive UI components without wrapping them, or their returns, using useObserver(), as per the usage documented in the 2nd to last code block of this guide: https://mobx-react.js.org/recipes-migration#hooks-to-the-rescue

The intended outcome is that items added to an observable list are reflected in UI.

Actual outcome

Added item are not reactively reflected in the UI. A force update will display these item

As a bonus, the autorun() on updates to the observable array also does not run.

How to reproduce the issue

https://codesandbox.io/s/useobserver-not-working-as-documented-g03v2

danielkcz commented 4 years ago

Have you even read documentation? You need an observer... https://mobx-react.js.org/observe-how

import { observer } from "mobx-react-lite";

const Display = observer(() => {...
danielkcz commented 4 years ago

Also... You cannot just react to whole list without iterating (or cloning) it.

autorun(() => console.log(toJS(store.items)));
dart200 commented 4 years ago

I understand the common pattern is to wrap things in observers, I'm interested in a reactive store that doesn't require me to do that, given that hooks alone can trigger re-renders.

Hence why I pointed to this specific portion of code in your documentation:

// use mobx-react@6.1.2 or `mobx-react-lite`
import { useObserver } from 'mobx-react'
function useUserData() {
  const { user, order } = useStores()
  return useObserver(() => ({
    username: user.name,
    orderId: order.id,
  }))
}

const UserOrderInfo = () => {
  // this works now just fine
  const { username, orderId } = useUserData()
  return (
    <div>
      {username} has order {orderId}
    </div>
  )
}

Are the docs wrong? Or am I misreading this?

dart200 commented 4 years ago

@FredyC ... Nvm, my issue was not cloning the arrays. Thanks.

Didn't need to wrap it though, feels better this way. ;)

whew ... thought i was going to give up on this and go back to redux. 👎