https://github.com/zapolnoch/mobx-with-query
Like react-query but for MobX and simpler
https://github.com/zapolnoch/mobx-with-query
mobx mobx-react query
Last synced: 3 months ago
JSON representation
Like react-query but for MobX and simpler
- Host: GitHub
- URL: https://github.com/zapolnoch/mobx-with-query
- Owner: zapolnoch
- License: mit
- Created: 2023-11-21T19:48:17.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-11-21T20:07:49.000Z (over 1 year ago)
- Last Synced: 2025-03-14T21:52:52.078Z (4 months ago)
- Topics: mobx, mobx-react, query
- Language: JavaScript
- Homepage: https://www.npmjs.com/package/mobx-with-query
- Size: 3.91 KB
- Stars: 6
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# WithQuery
It makes fetching and updating server state in your MobX-store a breeze.
## Usage
```ts
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:
```tsx
const Page = observer(() => {
const [store] = useState(() => new Store())
const { isLoading, data, error } = store.dataif (isLoading) return "Loading..."
if (error) return "An error has occurred: " + error.message
return
{data.name}
})
```## Config
The `onError` and `onSuccess` can be used to handle these events:
```ts
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:
```tsx
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])
})
```