Implement Mobx ViewModel in React Component state

1.2k views Asked by At

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?

2

There are 2 answers

0
levi On BEST ANSWER

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}
/>
5
Danila On

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