Question
Hey!
I'm in the process of refactoring an app which is using MST quite heavily, with the data loading logic making up quite a lot of the complexity.
I'd like to move this data-loading logic out of the MST stores and into react-query instead. This (contrived) example is what I have in mind:
import React from 'react'
import { types } from 'mobx-state-tree'
import { observer } from 'mobx-react-lite'
import { useQuery } from 'react-query'
const PersonModel = types.model('Person', {
id: types.identifier,
firstName: types.string,
lastName: types.string
}).views(self => ({
get fullName() {
return [self.firstName, self.lastName].join(' ')
}
}))
const usePerson = (id: string) => useQuery(
['person', id],
async () => PersonModel.create(await fetchPerson(id))
)
const Person: React.FC = observer(() => {
const { data } = usePerson(1);
return <span>Hello {data?.fullName}!</span>
})
This appears to work... however I'm encountering a concerning bug that's really difficult to reproduce: occasionally, computed properties all return undefined.
If I create the model from the useQuery() result, the problem doesn't occur:
const usePerson = (id: string) => {
const result = useQuery(['person', id], () => fetchPerson(id));
// Would probably memoise this, but keeping simple for brevity
const data = PersonModel.create(result.data);
return {
...result,
data
}
}
...but this feels less clean.
I'm anticipating the problem is something to do with how/when those computed properties are triggered, but my knowledge of the internals of MobX isn't strong enough to guess at why that might be. It would be great to get a sense check on this approach for combining the two libraries if anyone has any experience with this.
🙂 Thanks in advance!
Question
Hey!
I'm in the process of refactoring an app which is using MST quite heavily, with the data loading logic making up quite a lot of the complexity.
I'd like to move this data-loading logic out of the MST stores and into
react-queryinstead. This (contrived) example is what I have in mind:This appears to work... however I'm encountering a concerning bug that's really difficult to reproduce: occasionally, computed properties all return
undefined.If I create the model from the
useQuery()result, the problem doesn't occur:...but this feels less clean.
I'm anticipating the problem is something to do with how/when those computed properties are triggered, but my knowledge of the internals of MobX isn't strong enough to guess at why that might be. It would be great to get a sense check on this approach for combining the two libraries if anyone has any experience with this.
🙂 Thanks in advance!