All Projects → JumboInteractiveLimited → Redux Cache

JumboInteractiveLimited / Redux Cache

Licence: mit
Client side TTL caching strategy for redux applications

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Redux Cache

Ansible Role Redis
Ansible Role - Redis
Stars: ✭ 176 (-11.11%)
Mutual labels:  cache
Thinkgo
A lightweight MVC framework written in Go (Golang).
Stars: ✭ 184 (-7.07%)
Mutual labels:  cache
Elefant
Elefant, the refreshingly simple PHP CMS and web framework.
Stars: ✭ 188 (-5.05%)
Mutual labels:  cache
Akavache
An asynchronous, persistent key-value store created for writing desktop and mobile applications, based on SQLite3. Akavache is great for both storing important data as well as cached local data that expires.
Stars: ✭ 2,185 (+1003.54%)
Mutual labels:  cache
Recent Images
Do you noticed the new feature of Telegram or Instagram?! They show your latest images when you try to attach or post a picture. So I developed this library the same with lots of customization. Simple way to get all images of device based on date taken, name, id and other customization
Stars: ✭ 182 (-8.08%)
Mutual labels:  cache
Wechatvideocourse
《微信公众号+小程序快速开发》视频教程课件及代码
Stars: ✭ 185 (-6.57%)
Mutual labels:  cache
Ktvhttpcache
A powerful media cache framework.
Stars: ✭ 2,113 (+967.17%)
Mutual labels:  cache
Golib
Go Library [DEPRECATED]
Stars: ✭ 194 (-2.02%)
Mutual labels:  cache
Phpfastcache
A high-performance backend cache system. It is intended for use in speeding up dynamic web applications by alleviating database load. Well implemented, it can drops the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful.
Stars: ✭ 2,171 (+996.46%)
Mutual labels:  cache
Cacule Cpu Scheduler
The CacULE CPU scheduler is based on interactivity score mechanism. The interactivity score is inspired by the ULE scheduler (FreeBSD scheduler).
Stars: ✭ 185 (-6.57%)
Mutual labels:  cache
Dyld cache extract
A macOS utility to extract dynamic libraries from the dyld_shared_cache of macOS and iOS.
Stars: ✭ 180 (-9.09%)
Mutual labels:  cache
Buildbuddy
BuildBuddy is an open source Bazel build event viewer, result store, and remote cache.
Stars: ✭ 182 (-8.08%)
Mutual labels:  cache
Simple Spring Memcached
A drop-in library to enable memcached caching in Spring beans via annotations
Stars: ✭ 185 (-6.57%)
Mutual labels:  cache
Liget
NuGet server and cache running on kestrel in docker
Stars: ✭ 177 (-10.61%)
Mutual labels:  cache
Masterchief
C# 开发辅助类库,和士官长一样身经百战且越战越勇的战争机器,能力无人能出其右。
Stars: ✭ 190 (-4.04%)
Mutual labels:  cache
Flatcache
Implementation of Soroush Khanlou's Flat Cache.
Stars: ✭ 173 (-12.63%)
Mutual labels:  cache
Http Cache
High performance Golang HTTP middleware for server-side application layer caching, ideal for REST APIs
Stars: ✭ 184 (-7.07%)
Mutual labels:  cache
Scaffeine
Thin Scala wrapper for Caffeine (https://github.com/ben-manes/caffeine)
Stars: ✭ 195 (-1.52%)
Mutual labels:  cache
Drone Cache
A Drone plugin for caching current workspace files between builds to reduce your build times
Stars: ✭ 194 (-2.02%)
Mutual labels:  cache
Zbnetworking
AFNetworking4.X封装 GET/POST /PUT/PATCH /DELETE / Upload /DownLoad 网络请求 添加了请求缓存,断点下载,显示缓存大小,删除缓存,取消当前请求等功能
Stars: ✭ 186 (-6.06%)
Mutual labels:  cache

Build Status Coverage Status

redux-cache

This library provides an easy to use client side TTL caching strategy for redux applications.

Often, it is unnecessary to refetch data from an API if we know that it is unlikely to have changed within a certain period. By not fetching the data we are being friendly to mobile data users, limiting unnecessary API calls, and minimizing re-renders of applications due to state updates.

Installation

npm install -s redux-cache

Usage

Note: For a complete example, have a look at the example directory. You can clone this repo and actually start the example to see it working.

1. Add the cacheEnhancer to the store

Add the store enhancer to your redux store. Example:

import { compose, applyMiddleware, createStore } from 'redux'
import { cacheEnhancer } from 'redux-cache'

const store = createStore(
	reducer,
	undefined,
	compose(
		applyMiddleware(...),
		cacheEnhancer()
	)
)

This will enhance your store so that whenever you dispatch the invalidateCache action, it automatically will invalidate the cache for any provided reducers. This means you do not have to bother with the boilerplate for every single reducer. Great for larger apps!

2. Set up your reducer

Included are a couple of utilities for setting up your reducer to make it "cache enabled".

Firstly, the DEFAULT_KEY is what redux-cache will use for storing and clearing cache values unless told to use an additional cache key. Secondly is the generateCacheTTL function which will create a timestamp for you.

In your reducer:

// postsReducer.js

import { DEFAULT_KEY, generateCacheTTL } from "redux-cache";

const initialState = {
	[DEFAULT_KEY]: null
	// ...other keys
}

const postReducer = (state = initialState, action) => {
	switch (action.type) {
		case FETCH_POSTS_SUCCESS: {
			return {
				...state,
				[DEFAULT_KEY]: generateCacheTTL(),
				results: action.payload
			};
		}

		default: {
			return state;
		}
	}
}

We set up the key in the initial state and then on the successful fetch action we generate a new TTL time.

3. Check your cache before using an action

Before you fire off another get request, you should check if the cache is valid. A util fn - checkCacheValid() - has been provided:

// postsActions.js
import { checkCacheValid } from "redux-cache";

export const getPosts = () => (dispatch, getState) => {
	const isCacheValid = checkCacheValid(getState, "posts");
	if (isCacheValid) { return null; }

	dispatch({
		type: FETCH_POSTS_REQUEST
	});

	axios.get("https://jsonplaceholder.typicode.com/posts")
		.then((response) => {
				dispatch({
				type: FETCH_POSTS_SUCCESS,
				payload: response.data,
			});
		})
		.catch((error) => {
			console.log('error: ', error);
			dispatch({
				type: FETCH_POSTS_FAILURE,
				payload: error,
			});
		});
};

If the cache is valid, drop the action on the floor. This will stop any calls to the API being made.

4. Invalidating the cache

If you need to invalidate the cache for a reducer there is a utility action provided - invalidateCache. Just dispatch this with the reducer(s) you need to invalidate.

import { invalidateCache } from "redux-cache";

invalidateCache("posts");

API

cacheEnhancer([config])

  • arguments:
    • config - object
      • log - boolean - default: false. Will output to console when the invalidateCache is being processed. Useful for debugging.
      • cacheKey - string - default: DEFAULT_KEY. The cacheKey to be updating in your reducers when invalidating the cache.

generateCacheTTL([duration])

  • arguments:
    • duration - number - default: DEFAULT_DURATION_MS. A number representing miliseconds. To be added to the current time.

checkCacheValid(getState, reducerKey, [config])

  • arguments:
    • getState - function - The getState function provided by using redux-thunk which will be used to get the application state
    • reducerKey - string - The key of the reducer to check whether the cache is still valid
    • config
      • cacheKey - string - default: DEFAULT_KEY. The cacheKey to be checking.
      • accessStrategy - function - default: (state, reducerKey, cacheKey) => state[reducerKey][cacheKey]. Use this to overide the way in which the cacheKey is checked. This allows for greater configurability for applying the caching strategy to nested items in your reducer.

invalidateCache(reducers)

  • arguments
    • reducers - array (of strings) or single string - An array or string of reducers to invalidate.

Constants

  • DEFAULT_KEY - "cacheUntil"
  • DEFAULT_DURATION_MS - 600000 (in milliseconds). 10 minutes.

Tests

To run the tests:

npm run test

License:

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].