npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@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-query

mobx-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