Skip to content

Strategy for combining with react-query #1697

Description

@jonlambert

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!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions