Class

FluxCache

@psionic/flux.FluxCache(config)

Class representing a Flux cache. A Flux cache has a defined fetch function which can be used to fetch the data asynchronously. After the data has been fetched, it will be cached. The next time the data needs to be fetched, it will be taken from the cache, unless it was marked as stale.

New FluxCaches should be created with the createFluxCache function -- NOT with a new FluxCache() constructor. Otherwise, the Flux object will not be instantiated in the general FluxManager singleton, and functionality may break.

Constructor

# new FluxCache(config)

Parameters:
Name Type Attributes Description
config Object

The configuration object

id string

The ID to use for the FluxCache; should be unique among all other active Flux objects

fetch function

The function to call to asynchronously fetch the data to store in the cache, if non-stale data does not already exist in the cache

staleAfter Number <optional>

The amount of time to wait before declaring the data in the cache as stale; if this value is not passed, then the cache will not be marked stale in response to the age of the data in the cache

autofetchOnStale boolean <optional>

Whether or not to automatically fetch new data when the cache gets marked as stale

View Source flux/src/flux-cache/flux-cache.js, line 24

Methods

# clear()

Manually clears the data from the cache. Usually not needed unless a large amount of data is being stored in the cache and you wish to free up memory usage. Calling this function will automatically mark the cache as stale.

View Source flux/src/flux-cache/flux-cache.js, line 388

Example
// Create a FluxCache object
const profileCache = createFluxCache({
     id: 'profileCache',
     fetch: async () => getLargeAmountOfData(),
});

// Fetch the data for the cache
await profileCache.get();

// If the data is no longer needed, it can be manually cleared from the cache to free up memory
profileCache.clear();

# async get() → {Promise.<*>}

Retrieves the appropriate data from the cache, if it is available and non-stale, or externally via the Flux cache's fetch function if the data is not available or is stale in the cache.

If the cache is re-marked as stale while the Flux cache is running a fetch operation, the existing fetch operation will be restarted from scratch in order to ensure the most up-to-date data is used. See example 2.

View Source flux/src/flux-cache/flux-cache.js, line 177

Resolves with the data from either the cache or from the external fetch function

Promise.<*>
Examples
// Create a FluxCache object
const profileCache = createFluxCache({
     id: 'profileCache',
     fetch: async () => {
         await delay(5000);
         return { name: 'John' };
     }
});

// Read the value from the FluxCache for the first time (runs the fetch function passed to the cache; promise should take ~5s)
const profile = await profileCache.get(); // { name: 'John' }

// Read the value from the FluxCache for the second time (retrieves the stored data from the cache; promise should only take a few milliseconds)
const cachedProfile = await profileCache.get();
// Create a FluxState object
const userIDState = createFluxState({
     id: 'userIDState',
     value: 'John',
});

// Create a FluxCache object that relies on the userIDState Flux object
const userCache = createFluxCache({
     id: 'userCache',
     fetch: async () => {
         const userID = userIDState.get();
         // Mock an asynchronous data fetching delay
         await delay(delayTime)
         return { name: userID };
     },
     dependsOn: [userIDState],
});

// Initiate a `get` request for the cache
const getPromise = userCache.get();

// Before the `get` request resolves, change the userIDState value; this will cause the above `get` operation to restart w/ the new data
userIDState.set('Roni');

// Wait for the `getPromise` to resolve and retrieve the result
const result = await getPromise; // { name: 'Roni' } since the userIDState changed before the `get` operation resolved

# getCachedData() → {*}

Returns whatever data is currently stored in the cache, regardless of whether that data is stale or not. To note, unless manually cleared, the data from the last successful get call will remain stored in the cache until another get call resolves and updates the cache. This means it is possible to use this function while another get operation is running to retrieve the results from the last successfuly get operation.

View Source flux/src/flux-cache/flux-cache.js, line 432

The data currently stored in the cache, whether it is stale or not

*
Example
// Create a FluxState object
const userIDState = createFluxState({
     id: 'userIDState',
     value: 'John',
});

// Create a FluxCache object
const profileCache = createFluxCache({
     id: 'profileCache',
     fetch: async () => {
         // Mock a 5s delay before the data is resolved and stored in the cache
         await delay(5000);
         const userID = await userIDState.get();
         return { name: userID };
     },
});

// Fetch the first reading and store it in the cache
await profileCache.get(); // { name: 'John' }

// Update the `userIDState` to trigger a stale profile cache
userIDState.set('Roni');

// Start a new `get` operation to store the new data in the cache (but don't `await` the result)
profileCache.get(); // Will resolve to { name: 'Roni' } after 5 seconds

// Retrieve the data currently in the cache before the new data resolves and updates the cache
profileCache.getCachedData(); // { name: 'John' }

# getID() → {string}

Get the Flux object's ID.

View Source flux/src/flux-cache/flux-cache.js, line 442

The Flux object's ID

string

# getIsLoading() → {boolean}

Get a flag indicating whether the cache is currently loading data or not.

View Source flux/src/flux-cache/flux-cache.js, line 308

Flag indicating whether the cache is actively loading data or not

boolean
Example
// Create a FluxCache object
const profileCache = createFluxCache({
     id: 'profileCache',
     fetch: async () => {
         // Add an artifical 500ms delay before the data loads
         await delay(500);
         return { name: 'John' };
     },
});

// The cache is not loading data in the beginning
let isStale = profileCache.getIsLoading(); // false

// Initiate the load of the data
profileCache.get();

// The cache is now loading data
isStale = profileCache.getIsLoading(); // true

// Wait for 500ms for the data to fully load
await delay(500);

// The cache is no longer loading data
isStale = profileCache.getIsLoading(); // false

# getStale() → {boolean}

Getter for the stale flag on the cache.

View Source flux/src/flux-cache/flux-cache.js, line 272

The flag indicating whether the data in the cache is currently stale or not

boolean
Example
// Create a FluxCache object
const profileCache = createFluxCache({
     id: 'profileCache',
     fetch: async () => {
         return { name: 'John' };
     },
     staleAfter: 5000, // Data will be marked as stale 5s after it is cached
});

// The cache is always stale when first initialized
let isStale = profileCache.getStale(); // true

// Fetch the profile to remove the stale state
profileCache.get();

// The cache will no longer be stale, since the profile was just fetched
isStale = profileCache.getStale(); // false

// If we wait 5 seconds, the data will become stale since we set `staleAfter` to `5000`
await delay(5000);
isStale = profileCache.getStale(); // true

# setStale(isStale)

Manually sets the stale state of the FluxCache. If setting the stale state to false, and the staleAfter value is set for the FluxCache, the stale timer will start immediately after setting the stale state to false.

Parameters:
Name Type Description
isStale boolean

Flag indicating whether the cache is stale or not

View Source flux/src/flux-cache/flux-cache.js, line 366

Example
// Create a FluxCache object
const profileCache = createFluxCache({
     id: 'profileCache',
     fetch: async () => {
         return { name: 'John' };
     }
});

// Set the stale state of the cache to `false`, manually
profileCache.setStale(false);

// Set the stale state of the cache to `true`, manually
profileCache.setStale(true);

# updateFetch(fetch)

Updates the function this cache uses to externally fetch the data it stores. Calling this function will automatically mark the cache as stale.

Parameters:
Name Type Description
fetch function

The new function to call to fetch data to store in this cache

View Source flux/src/flux-cache/flux-cache.js, line 336

Example
// Create a FluxCache object
const profileCache = createFluxCache({
     id: 'profileCache',
     fetch: async () => {
         return { name: 'John' };
     }
});

// Fetch the initial profile; the cache will not be marked as stale anymore
profileCache.get();

// Update the fetch function to retrieve a different user's profile; the cache will immediately be marked as stale
profileCache.updateFetch(async () => {
     return { name: 'Roni' };
});