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

react-query-cache-persistent

v1.0.0

Published

This persistor extends [QueryCache](https://tanstack.com/query/v5/docs/reference/QueryCache) to persist the cache in a simple way without hydration/dehydration phase.

Downloads

569

Readme

react-query-cache-persistent

This persistor extends QueryCache to persist the cache in a simple way without hydration/dehydration phase.

The biggest advantage in terms of performance is, that the persistor stores the queries by each single query instead of storing the whole cache on each change.

This is huge if your cache is several megabytes in size.

⚠️ The only drawback is that this only works in a synchronous way. You cannot use this if your storage only provides asynchronous methods to get/set the cache. See How it works

Usage

See below for examples.

import { PersistentQueryCache } from 'react-query-cache-persistent'

// Your implementation. See below for examples.
const persistentQueryCache = new PersistentQueryCache({
  add: (query) => {},
  updated: (query) => {},
  removed: (query) => {},
})

const queryClient = new QueryClient({ queryCache: persistentQueryCache })

Examples

Web

Uses localStorage as storage.

localStorage

import { PersistentQueryCache } from 'react-query-cache-persistent'

const persistentQueryCache = new PersistentQueryCache({
  add: (query) => {
    const item = window.localStorage.getItem(`queryCache.${query.queryHash}`)

    if (item != null) {
      query.state = JSON.parse(item)
    }

    window.localStorage.setItem(`queryCache.${query.queryHash}`, JSON.stringify(query.state))
  },
  updated: (query) => {
    window.localStorage.setItem(`queryCache.${query.queryHash}`, JSON.stringify(query.state))
  },
  removed: (query) => {
    window.localStorage.removeItem(`queryCache.${query.queryHash}`)
  },
})

const queryClient = new QueryClient({ queryCache: persistentQueryCache })

React Native

Uses @op-engineering/op-sqlite as storage. But you can use any sqlite solution as long it supports synchronous get/set.

The example below writes each query as a table row into a sqlite database

queryCache.sqlite3

import {
  ANDROID_DATABASE_PATH,
  IOS_LIBRARY_PATH,
  PreparedStatementObj,
  open,
} from '@op-engineering/op-sqlite'
import { Query } from '@tanstack/react-query'
import { Platform } from 'react-native'

import { PersistentQueryCache } from 'react-query-cache-persistent'

const tableName = 'queryCache'

const connect = () => {
  return open({
    name: 'queryCache.sqlite3',
    location: Platform.OS === 'ios' ? IOS_LIBRARY_PATH : ANDROID_DATABASE_PATH,
  })
}

let db = connect()

db.execute(
  `CREATE TABLE IF NOT EXISTS ${tableName} (queryHash TEXT NOT NULL UNIQUE, queryState TEXT) STRICT;`
)

const selectStmt = db.prepareStatement(`SELECT queryState FROM ${tableName} WHERE queryHash = ?;`)
const insertStmt = db.prepareStatement(
  `INSERT INTO ${tableName} (queryHash, queryState) VALUES (?, ?) ON CONFLICT(queryHash) DO UPDATE SET queryState=excluded.queryState;`
)
const deleteStmt = db.prepareStatement(`DELETE FROM ${tableName} WHERE queryHash = ?;`)

/**
 * Executes the prepared statement with the given parameters
 *
 * Will retry once if it throws `[OP-SQLite] DB is not open`
 */
const runStmt = (stmt: PreparedStatementObj, params: string[]) => {
  try {
    stmt.bind(params)
    return stmt.execute()
  } catch (error: unknown) {
    if (`${error}`.includes('[OP-SQLite] DB is not open')) {
      // retry once (on iOS the first execution fails on first start, but only in the context of PersistQueryCache::add)
      db = connect()
      stmt.bind(params)
      const result = stmt.execute()
      console.warn(`First execution failed. Second try worked.`)
      return result
    }
    console.warn(`Failed to execute query: "${error}".`)
    throw error
  }
}

export const queryCache = new PersistQueryCache({
  add: (query: Query) => {
    const result = runStmt(selectStmt, [query.queryHash])

    const firstRow = result.rows?._array[0]
    if (firstRow != null) {
      try {
        query.state = JSON.parse(firstRow.queryState)
      } catch (error: unknown) {
        console.warn(`Failed to hydrate state for query "${query.queryHash}": ${error}`)
      }
    }

    runStmt(insertStmt, [query.queryHash, JSON.stringify(query.state)])
  },

  updated: (query: Query) => {
    runStmt(insertStmt, [query.queryHash, JSON.stringify(query.state)])
  },

  removed: (query: Query) => {
    runStmt(deleteStmt, [query.queryHash])
  },
})

How it works

TODO

License

MIT License.