0

For example I have Store and App when I try to destruct Store's params useObserver not working React not re-render app when Store's title changes. But if I will not destruct params and will use directly in return like Store.title it will work. Why its working like this and how to fix it?

-- Store.js --

import { observable, action } from 'mobx'
class Store{
  @observable title = "";

  @action handleTitleChange({ target: {value} }){
     this.title = value;
  }
}

-- App.js-- Not Working

import React from 'react'
import { useObserver } from 'mobx-react'
import Store from 'store'

export default () => {
  const { title, handleTitleChange } = Store
  return useObserver(() =>{
    <input value={title} onChange={handleTitleChange}>
  })
}

-- App2.js-- Working

import React from 'react'
import { useObserver } from 'mobx-react'
import Store from 'store'

export default () => {
  const { handleTitleChange } = Store
  return useObserver(() =>{
    <input value={Store.title} onChange={handleTitleChange}>
  })
}
Aliaga Aliyev
  • 415
  • 1
  • 6
  • 22

1 Answers1

1

This situation was explained in "Understanding reactivity" part of the docs https://mobx.js.org/understanding-reactivity.html

You are dereferencing value outside of observer decorator (useObserver if your case). You either need to do it like you did in the second example, or wrap whole component with observer, like that:

import React from 'react'
import { observer } from 'mobx-react'
import Store from 'store'

export default observer(() => {
  const { title, handleTitleChange } = Store
  return <input value={title} onChange={handleTitleChange} />
})
Danila
  • 15,606
  • 2
  • 35
  • 67