1.0.0 • Published 6 months ago

mobx-with-query v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

WithQuery

It makes fetching and updating server state in your MobX-store a breeze.

Usage

import { WithQuery } from "mobx-with-query"

class Store {
  constructor() {
    makeAutoObservable(this)
  }

  data = new WithQuery(() =>
    fetch("https://api.github.com/repos/tannerlinsley/react-query"),
  )
}

In your React-component:

const Page = observer(() => {
  const [store] = useState(() => new Store())
  const { isLoading, data, error } = store.data

  if (isLoading) return "Loading..."

  if (error) return "An error has occurred: " + error.message

  return <div>{data.name}</div>
})

Config

The onError and onSuccess can be used to handle these events:

class Store {
  data = new WithQuery(Api.getMethod, {
    onError: () => alert("Server Error. Please try again later"),
    onSuccess: () => alert("Completed successfully"),
  })
}

You can disable automatic data loading using loadOnMount. In addition, you can transform the response using mapping:

class Store {
  project = new WithQuery(Api.getProject, {
    loadOnMount: false,
    transform: (data) => data?.name.toUpperCase(),
  })
}

const Page = observer(() => {
  const [store] = useState(() => new Store())
  const { id } = useParams()

  useEffect(() => {
    project.load(id)
  }, [id])
})
1.0.0

6 months ago