0

I want to use Mobx ViewModel (from mobx-utils) in a functional component in React. Well, My model in this case is a state. (e.g - company in the next line):

const [company, setCompany] = useState(store.companyObservable)

And according to that, the initial of the view model will be look like this:

const vm = createViewModel(company);

And the use of it in the template will look like this:

 <Input        
   value={vm.name}
   onChange={e => vm.name = e.target.value }
 />

But in this way, Even though that the initial value will get in to the input. The input now not editable. Which is quite understandable because he is not in state.

So, how can I implement this thing in the right way?

halfer
  • 19,824
  • 17
  • 99
  • 186
levi
  • 1,077
  • 2
  • 11
  • 24

2 Answers2

0

Input is not editable because if you call this const vm = createViewModel(company) inside render then each time new viewModel will be created from your company and all your fields will be reset basically.

What you can do is also just store your ViewModel inside state so it reference will be preserved between re renders.

const [company, setCompany] = useState(store.companyObservable)
const [vm] = useState(createViewModel(company)) // Since you don't need to change it then you don't even need to destructure setter
Danila
  • 15,606
  • 2
  • 35
  • 67
  • Sorry on the late response. What do you mean that am not need to change it. I need to change it as i show in my example (in the onChange function). and in this way i can not change it. i am wrong? – levi Nov 02 '20 at 08:14
  • You change `name`, not the model itself. The reference stays the same – Danila Nov 02 '20 at 19:02
  • How can i change the name without the model? do you can add to your answer a code example? – levi Nov 03 '20 at 07:35
  • You don't need to change whole model just to change `name`. `name` is just a property of a model. I've provided code example in my answer already, have you tried it? – Danila Nov 03 '20 at 09:29
  • Yes, I have already inserted this line. I mean to the code that update the propery, in the onChange function. anyway, i solved this. my answer. – levi Nov 03 '20 at 10:56
0

Solved by useing 'computed' like this:

//store
@observable
companyDetails: ICompanyDetails = { id: 0 }

@computed
get companyDetailsViewModel() {
    return createViewModel(this.companyDetails)
}

//component
 const vm = companyStore.companyDetailsViewModel

<Input
   value={vm.name}
   onChange={e => vm.name = e.target.value}
/>
levi
  • 1,077
  • 2
  • 11
  • 24