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

@servicetitan/tanstack-query-mobx

v4.2.1

Published

TanStack Query (React Query) integration for MobX stores with react-ioc dependency injection. Provides declarative data fetching, caching, synchronization, and state management with automatic query deduplication and observable state.

Downloads

7,843

Readme

@servicetitan/tanstack-query-mobx

TanStack Query integration for MobX stores with @servicetitan/react-ioc dependency injection. Provides declarative data fetching, caching, and state management with automatic query deduplication.

Installation

npm install @servicetitan/tanstack-query-mobx

Quick Start

1. Provide the Query Client

import { getQueryClient } from '@servicetitan/tanstack-query-mobx';

export const App = provide({
    singletons: [getQueryClient()],
})(observer(() => <YourApp />));

2. Create a Store

import { QueryApiStore, QueryApiOptions } from '@servicetitan/tanstack-query-mobx';

@injectable()
export class JobsStore extends QueryApiStore<Job[]> {
    @inject(JobsApi) private api?: JobsApi;

    get queryOptions(): QueryApiOptions<Job[]> {
        return {
            queryKey: ['jobs'],
            queryFn: async () => (await this.api?.getJobs())?.data ?? [],
        };
    }
}

3. Use in Components

const [{ data, isLoading }] = useDependencies(JobsStore);

Key Concepts

Query Keys - Arrays that uniquely identify queries. Changes trigger automatic refetch:

queryKey: ['jobs', jobId]; // Refetches when jobId changes

Observable State - data, initialized, isLoading, isFetching, isError, error

Stale Time - Default 10 minutes. Set staleTime: 0 for always fresh, Infinity for never stale.

Common Patterns

Mutations (MutationApi reference)

snooze = this.addMutation<void, { id: number }>(() => ({
    mutationFn: async arg => (await this.api?.snooze(arg.id))?.data,
    invalidatedQueries: [['tasks']], // Refetch after success
}));

await this.snooze.runMutation({ id: 123 });

See runMutation() JSDoc for advanced options like custom onSuccess/onError handlers.

Multiple Queries (QueryApiStore reference)

Your primary query should use the queryOptions getter (shown in Quick Start). Use addQuery() only for secondary queries alongside it:

stats = this.addQuery<Stats>(() => ({
    queryKey: ['stats'],
    queryFn: async () => (await this.api?.getStats())?.data,
}));

Use addQuery() in your store to manage multiple independent queries. Each query has its own lifecycle and state.

Shared Clients (Micro-Frontends)

For micro-frontend architectures where multiple app instances need to share query cache, use shared clients at the provider or query level.

Client types:

  • 'page' - Uses reference counting. Disposes when the last component using getQueryClient('page') unmounts.
  • 'app' - Persists until browser refresh/close. Only available via globalClient option.

See getQueryClient JSDoc for provider-level examples and QueryApiOptions.globalClient JSDoc for query-level examples.

Data-Driven Queries (QueryApiOptions reference)

queryKey: ['logs', jobId],  // Auto-refetches when jobId changes
enabled: jobId > 0,         // Only runs when condition is true

MobX reactions automatically track queryKey dependencies. When jobId changes, the query refetches.

API Reference

All classes have comprehensive TSDoc comments - use your IDE's intellisense or read the source.

Core Classes

QueryApiStore - Base class for query stores

  • Extend this to create stores that fetch and cache data
  • Provides observable data, isLoading, error, and initialized properties
  • Use addQuery() to add multiple queries and addMutation() for mutations
  • See JSDoc for full lifecycle methods

QueryApi - Individual query manager

  • Manages a single TanStack Query with MobX integration
  • Usually created via addQuery() in QueryApiStore
  • Methods: invalidate(), updateQueryData(), cancel(), refetch()
  • See JSDoc for lifecycle and state management details

MutationApi - Mutation manager for create/update/delete operations

  • Use runMutation(args, options?) to execute with automatic query invalidation
  • Provides observable isPending, isSuccess, isError, error state
  • Configure invalidatedQueries to automatically refetch after mutation success
  • See JSDoc for full configuration options and examples

Configuration Types

QueryApiOptions - Full query configuration extending TanStack Query's QueryObserverOptions

  • queryKey, queryFn, staleTime, enabled, etc.
  • Additional: disposeQuery, autoInitialize, onSuccess, onError, globalClient

MutationApiOptions - Full mutation configuration extending TanStack Query's MutationObserverOptions

  • mutationFn, onSuccess, onError, etc.
  • Additional: invalidatedQueries, globalClient

See TanStack Query docs for core query concepts and all standard options.

Learn More

Source Code & Documentation

All classes, interfaces, and methods have comprehensive TSDoc comments. Explore the source for detailed API documentation:

Core Implementations

Configuration Types

Utilities

External Resources

Testing

import { ContainerBuilder } from '@servicetitan/tanstack-query-mobx/test';

const { container, initialize } = new ContainerBuilder().add(JobsStore).add(JobsApi).build();

jest.spyOn(container.get(JobsApi), 'getJobs').mockResolvedValue({
    data: [{ id: 1, title: 'Job' }],
});

await initialize(); // Runs lifecycle + waits for initialized
expect(container.get(JobsStore).data).toHaveLength(1);

Testing Utilities

All testing utilities have comprehensive JSDoc comments with examples. Explore the source for detailed API documentation:

ContainerBuilder - Test container builder for dependency injection

  • Simplifies setting up stores and dependencies for testing
  • Methods: add(), build(), initialize(), addQueryClient()
  • Automatically waits for all stores and queries to initialize

waitFor - MobX reaction-based wait helper

  • Waits for observable conditions to become true
  • Returns promise that resolves when condition is met

SpyBuilder - Abstract base class for mocking API services

  • Create mock API services with jest spies
  • Methods: add(), getSpy()
  • Utilities: createAxiosResponse(), createAxiosError()

License

Part of the @servicetitan/anvil-uikit-contrib monorepo.