Cache System

Caching view methods

There are two kinds of cache systems to be used. They are Memory Cache and Storage Cache.

Memory Cache: will be cleared when the app refreshes, as its data lives in memory only. Storage Cache: The data will remain even when the browser tab is refreshed. Data is persisted using Local Storage.

When instantiating a cache, you need to provide the expirationTime (in seconds). This is used to know when the cache should be returned instead of making a real contract call. When the cache expires, a real call to the contract is made. Each contract's method has its own time of expiration.

// web3Api.ts
import naxios, { StorageCache } from '@wpdas/naxios'

const naxiosInstance = new naxios({
  contractId: CONTRACT_ID,
  network: 'testnet',
})

// ...

/**
 * Another Contract API (not using cache)
 */
export const socialDBcontractApi = naxiosInstance.contractApi({
  contractId: 'v1.social08.testnet'
})

/**
 * Cached - Greeting Contract API
 */
export const cachedGreetingContractApi = naxiosInstance.contractApi({
  contractId: 'dev-1692221685438-15421910364142',
  cache: new StorageCache({ expirationTime: 5 * 60 }), // 5 minutes
})

Then, to use cached view, you can just pass the configuration object saying you want to use cached data.

import { cachedGreetingContractApi } from './web3Api'

// Fetch Greetings [free]
const args: {}
const config: { useCache: true }
cachedGreetingContractApi.view<string>('get_greeting', args, config)
  .then((response) => console.log(response))

Last updated