@mobx-query/core
v0.3.0
Published
**Reactive server-state entities for MobX, powered by TanStack Query.**
Downloads
206
Readme
mobx-query
Reactive server-state entities for MobX, powered by TanStack Query.
mobx-query lets you keep TanStack Query's fetching, caching, invalidation, and mutation lifecycle while working with real MobX domain objects.
Install
npm install @mobx-query/core mobx mobx-react-lite @tanstack/react-querymobx-query examples use MobX with TC39 decorator syntax:
{
"compilerOptions": {
"experimentalDecorators": false,
"useDefineForClassFields": true
}
}Quick Start
1. Define an Entity
Entities contain observable state and lifecycle methods. onEntityDidFetch is
called when data comes from a query. onEntityDidCreate is called when a create
mutation builds an optimistic client-side entity.
import { observable } from "mobx";
import { Entity, generateEntityId } from "@mobx-query/core";
type TodoData = {
id: string;
title: string;
completed: boolean;
};
type CreateTodoInput = {
title: string;
};
export class Todo extends Entity<string> {
id = "";
@observable accessor title = "";
@observable accessor completed = false;
protected onEntityDidFetch(data: TodoData) {
this.id = data.id;
this.title = data.title;
this.completed = data.completed;
}
protected onEntityDidCreate(data: CreateTodoInput) {
this.id = generateEntityId(Todo);
this.title = data.title;
this.completed = false;
}
readonly updateMutation = this.mutationUpdate({
mutationFn: async () => {
await this.ctx.api.updateTodo(this.id, {
title: this.title,
completed: this.completed,
});
},
});
readonly deleteMutation = this.mutationDelete({
mutationFn: async () => {
await this.ctx.api.deleteTodo(this.id);
},
});
}2. Define a Collection
Collections are now first-class. They own the entity constructor, collection state, list/detail queries, and create mutations for that entity type.
import { EntityCollection } from "@mobx-query/core";
import { Todo } from "./Todo";
export class TodosCollection extends EntityCollection<typeof Todo> {
constructor() {
super(Todo);
}
readonly allQuery = this.queryMany({
queryKey: () => ["all"],
queryFn: async () => {
return this.ctx.api.getTodos();
},
});
readonly byIdQuery = this.queryOne({
queryKey: () => ["byId"],
queryFn: async (id: string) => {
return this.ctx.api.getTodo(id);
},
});
readonly createMutation = this.mutationCreate({
mutationFn: async (input, entity) => {
await this.ctx.api.createTodo({
id: entity.id,
title: entity.title,
completed: entity.completed,
});
},
});
}3. Register Context Types
The context must include a TanStack QueryClient. Add any app services you want
to access from this.ctx.
import type { QueryClient } from "@tanstack/react-query";
type Api = {
getTodos(): Promise<TodoData[]>;
getTodo(id: string): Promise<TodoData>;
createTodo(data: TodoData): Promise<void>;
updateTodo(id: string, data: Omit<TodoData, "id">): Promise<void>;
deleteTodo(id: string): Promise<void>;
};
declare global {
namespace MobXQuery {
interface RegisteredContext {
context: {
queryClient: QueryClient;
api: Api;
};
}
}
}4. Create the Client
MQClient receives a rootStore factory that returns your collections.
import { QueryClient } from "@tanstack/react-query";
import { createReactContext, MQClient } from "@mobx-query/core";
import { TodosCollection } from "./TodosCollection";
function rootStore() {
return {
todos: new TodosCollection(),
};
}
export type RootStore = ReturnType<typeof rootStore>;
export function initMQClient(queryClient: QueryClient, api: Api) {
return new MQClient<RootStore>({
rootStore,
context: {
queryClient,
api,
},
});
}
export const { Provider: MQProvider, useContext: useMQ } =
createReactContext<MQClient<RootStore>>();5. Use It in React
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { observer } from "mobx-react-lite";
import { MQProvider, initMQClient, useMQ } from "./mq";
const queryClient = new QueryClient();
const mqClient = initMQClient(queryClient, api);
export function App() {
return (
<QueryClientProvider client={queryClient}>
<MQProvider client={mqClient}>
<TodoList />
</MQProvider>
</QueryClientProvider>
);
}
const TodoList = observer(() => {
const client = useMQ();
const todos = client.rootStore.todos.allQuery.useSuspenseQuery();
const createTodo = client.rootStore.todos.createMutation.useMutation();
return (
<section>
<button onClick={() => createTodo({ title: "Write README" })}>
Add todo
</button>
<ul>
{todos.map((todo) => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.completed}
onChange={() => {
todo.completed = !todo.completed;
todo.updateMutation.mutate();
}}
/>
{todo.title}
</label>
</li>
))}
</ul>
</section>
);
});Core Concepts
Entities
An Entity is a MobX class with an id, observable fields, and lifecycle
methods:
| API | Purpose |
| --- | --- |
| onEntityDidFetch(data) | Required. Hydrates the entity from query data. |
| onEntityDidCreate(data) | Optional. Hydrates an optimistic entity from create input. |
| $isDirty | true after an observable field changes. |
| $state | Mutation state: pending, confirmed, or failed. |
| $reset() | Restores changed fields to their last fetched values. |
Use entity helpers for operations scoped to an existing entity:
readonly updateMutation = this.mutationUpdate({ mutationFn });
readonly deleteMutation = this.mutationDelete({ mutationFn });
readonly labelsQuery = this.queryFragmentMany({ entity: Label, queryKey });
readonly ownerQuery = this.queryFragmentOne({ entity: User, queryKey });Collections
An EntityCollection stores all entities of one type and exposes observable
collection state:
| API | Purpose |
| --- | --- |
| $collection | Underlying Map<EntityId, Entity>. |
| $array | Computed array of non-deleted entities. |
| $size | Current collection size. |
| $deletedIds | Optimistically deleted ids hidden from query results. |
| $clientOnlyIds | Optimistically created ids not yet confirmed by the server. |
| $invalidateQueries() | Invalidates all TanStack queries for the entity type. |
| $cancelQueries() | Cancels all TanStack queries for the entity type. |
Use collection helpers for entity-type level operations:
readonly listQuery = this.queryMany({ queryKey, queryFn });
readonly detailQuery = this.queryOne({ queryKey, queryFn });
readonly createMutation = this.mutationCreate({ mutationFn });Queries
queryMany and queryOne return MobX entities, not raw JSON.
const todos = todosCollection.allQuery.useSuspenseQuery();
const todo = todosCollection.byIdQuery.useSuspenseQuery(todoId);Available query methods include:
useSuspenseQuery(args)useDeferredQuery(args)useQuery(args, meta)useIsFetching(args)prefetch(args)ensureData(args)invalidate(args)setQueryData(data, args)
queryKey defines the stable base key. The final TanStack query key is prefixed
with the entity class name and query type, then receives the runtime args.
Mutations
Create mutations are declared on collections and receive both the original input and the optimistic entity:
readonly createMutation = this.mutationCreate({
mutationFn: async (input, entity) => {
await this.ctx.api.createTodo({ id: entity.id, title: input.title });
},
});Update and delete mutations are declared on entities and are automatically bound
to this:
readonly updateMutation = this.mutationUpdate({
mutationFn: async () => {
await this.ctx.api.updateTodo(this.id, { title: this.title });
},
});Mutations support TanStack mutation options such as retry, gcTime,
networkMode, scope, meta, and throwOnError, plus mobx-query optimistic
options:
import {
OptimisticMutationErrorStrategy,
OptimisticMutationInvalidationStrategy,
} from "@mobx-query/core";
readonly updateMutation = this.mutationUpdate({
invalidationStrategy: OptimisticMutationInvalidationStrategy.NONE,
errorStrategy: OptimisticMutationErrorStrategy.KEEP,
mutationFn: async () => {
await this.ctx.api.updateTodo(this.id, { title: this.title });
},
});Status
This library is in early development. APIs may continue to change before a
stable 1.0 release.
Documentation
Full documentation is available at mobx-query-docs.vercel.app.
License
MIT
