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 🙏

© 2024 – Pkg Stats / Ryan Hefner

mobx-tanstack-query

v3.1.37

Published

MobX wrappers for Tanstack Query (Core)

Downloads

2,172

Readme

mobx-tanstack-query

NPM version test status build status npm download bundle size

MobX wrapper for Tanstack Query Core package

What package supports

Queries -> MobxQuery

Class wrapper for @tanstack-query/core queries with MobX reactivity

Usage

Create an instance of MobxQuery with queryKey and queryFn parameters

const query = new MobxQuery({
  queryClient,
  abortSignal, // Helps you to automatically clean up query  
  queryKey: ['pets'],
  queryFn: async ({ signal, queryKey }) => {
    const response = await petsApi.fetchPets({ signal });
    return response.data;
  },
});  

Features

enableOnDemand option

Query will be disabled until you request result for this query
Example:

const query = new MobxQuery({
  //...
  enableOnDemand: true
});
// happens nothing
query.result.data; // from this code line query starts fetching data

dynamic options

Options which can be dynamically updated for this query

const query = new MobxQuery({
  // ...
  options: () => ({
    enabled: this.myObservableValue > 10,
    queryKey: ['foo', 'bar', this.myObservableValue] as const,
  }),
  queryFn: ({ queryKey }) => {
    const myObservableValue = queryKey[2];
  }
});

dynamic queryKey

Works the same as dynamic options option but only for queryKey

const query = new MobxQuery({
  // ...
  queryKey: () => ['foo', 'bar', this.myObservableValue] as const,
  queryFn: ({ queryKey }) => {
    const myObservableValue = queryKey[2];
  }
});

P.S. you can combine it with dynamic (out of box) enabled property

const query = new MobxQuery({
  // ...
  queryKey: () => ['foo', 'bar', this.myObservableValue] as const,
  enabled: ({ queryKey }) => queryKey[2] > 10,
  queryFn: ({ queryKey }) => {
    const myObservableValue = queryKey[2];
  }
});

method update()

Update options for query (Uses QueryObserver.setOptions)

hook onDone()

Subscribe when query has been successfully fetched data

hook onError()

Subscribe when query has been failed fetched data

method invalidate()

Invalidate current query (Uses queryClient.invalidateQueries)

method reset()

Reset current query (Uses queryClient.resetQueries)

method setData()

Set data for current query (Uses queryClient.setQueryData)

property isResultRequsted

Any time when you trying to get access to result property this field sets as true
This field is needed for enableOnDemand option
This property if observable

property result

Observable query result (The same as returns the useQuery hook)

About enabled

All queries are enabled (docs can be found here) by default, but you can set enabled as false or use dynamic value like ({ queryKey }) => !!queryKey[1]
You can use update method to update value for this property or use dynamic options construction (options: () => ({ enabled: !!this.observableValue }))

About refetchOnWindowFocus and refetchOnReconnect

They will not work if you will not call mount() method manually of your QueryClient instance which you send for your queries, all other cases dependents on query stale time and enabled properties.
Example:

import { hashKey, QueryClient } from '@tanstack/query-core';

const MAX_FAILURE_COUNT = 3;

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      throwOnError: true,
      queryKeyHashFn: hashKey,
      refetchOnWindowFocus: 'always',
      refetchOnReconnect: 'always',
      staleTime: 5 * 60 * 1000,
      retry: (failureCount, error) => {
        if ('status' in error && Number(error.status) >= 500) {
          return MAX_FAILURE_COUNT - failureCount > 0;
        }
        return false;
      },
    },
    mutations: {
      throwOnError: true,
    },
  },
});

queryClient.mount(); // enable all subscriptions for online\offline and window focus/blur

Mutations -> MobxMutation

Class wrapper for @tanstack-query/core mutations with MobX reactivity

Usage

Create an instance of MobxMutation with mutationFn parameter

const mutation = new MobxMutation({
  queryClient,
  abortSignal, // Helps you to automatically clean up mutation  
  mutationFn: async ({ signal, queryKey }) => {
    const response = await petsApi.createPet({ name: 'Fluffy' }, { signal });
    return response.data;
  },
});  

Features

method mutate(variables, options?)

Runs the mutation. (Works the as mutate function in useMutation hook)

hook onDone()

Subscribe when mutation has been successfully finished

hook onError()

Subscribe when mutation has been finished with failure

method reset()

Reset current mutation

property result

Observable mutation result (The same as returns the useMutation hook)

InfiniteQueries -> MobxInfiniteQuery

See docs for MobxQuery

Usage

  1. Install dependencies
pnpm add @tanstack/query-core mobx-tanstack-query
  1. Create QueryClient instance
// @/shared/lib/tanstack-query/query-client.ts
import { hashKey, QueryClient } from '@tanstack/query-core';

const MAX_FAILURE_COUNT = 3;

export const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      throwOnError: true,
      queryKeyHashFn: hashKey,
      refetchOnWindowFocus: 'always',
      refetchOnReconnect: 'always',
      staleTime: 5 * 60 * 1000,
      retry: (failureCount, error) => {
        if ('status' in error && Number(error.status) >= 500) {
          return MAX_FAILURE_COUNT - failureCount > 0;
        }
        return false;
      },
    },
    mutations: {
      throwOnError: true,
    },
  },
});

queryClient.mount(); // enable all subscriptions for online\offline and window focus/blur
  1. Use it
const petsListQuery = new MobxQuery({
  queryClient,
  queryKey: ['pets'],
  queryFn: async ({ signal, queryKey }) => {
    const response = await petsApi.fetchPets({ signal });
    return response.data;
  },
});

const addPetsMutation = new MobxMutation({
  queryClient,
  mutationFn: async (payload: { petName: string }) => {
    const response = await petsApi.createPet(payload);
    return response.data;
  },

  onSuccess: (data) => {
    rootStore.notifications.push({
      type: 'success',
      title: `Pet created successfully with name ${data.name}`,
    });
    petsListQuery.invalidate();
  },
  onError: (error) => {
    rootStore.notifications.push({
      type: 'danger',
      title: 'Failed to create pet',
    });
  }
});

addPetsMutation.mutate({ petName: 'fluffy' });