Skip to content

Instantly share code, notes, and snippets.

View malectro's full-sized avatar

Kyle Warren malectro

View GitHub Profile

Redux TTL

The Premise

Currently a request to the api for filtered data is inserted into our store in a normalized fashion.

For example, getting audience-members/${audienceMemberId}/due-events returns a set of DueEvents, which are dumped in a single object that holds all due events regardless of audience member (or any other filter properties).

Then when the list is rendered, a selector refilters the DueEvents stored in the heap by audienceMemberId.

@malectro
malectro / expander.jsx
Created June 1, 2017 22:48
a simple expand/collapse container for single components
// @flow
import React, {Component, Children} from 'react';
import {findDOMNode} from 'react-dom';
import {TransitionGroup} from 'react-transition-group';
const OnlyChild = ({children}) => (
Children.toArray(children)[0] || null
);
export const cached = ({ttl = 60000}) => wrappedFunc => {
// require the action creator to have a KEY
if (!wrappedFunc.KEY) {
throw new Error('Must use key() decorator first before fetching');
}
// the higher order action creator
const cachedWrapped = (...args) => (dispatch, getState) => {
const keyValue = wrappedFunc.KEY.apply(this, args);
export const key = keyFunc => (
wrappedFunc => {
wrappedFunc.KEY = keyFunc;
return wrappedFunc;
};
);
@require_auth
@require_admin
def get(self):
args = self.get_parser().parse_args()
return User.get_by_id(args.id)
const getUser = (userId) => (dispatch, getState) => {
// create a unique key for this request
const key = `@@getUser:${userId}`;
// if the action creator has already fired off a request, return it
const fetching = getState().fetching[key];
if (fetching) {
return fetching;
}
const getUser = flow([
key(userId => `@@getUser:${userId}`),
fetching(),
cached({ttl: 60000}),
])(userId =>
api.get(`/user/${userId}`).then(user =>
dispatch(receiveUser(user))
)
);
const key = generator => actionCreator => {
actionCreator.keyGenerator = generator;
return actionCreator;
};
const usersReducer = (state = {users: {}, fetching: {}, cache: {}}, {type, payload}) => {
switch (type) {
case START_FETCHING:
return {
...state,
fetching: {
...state.fetching,
[payload.userId]: payload.promise,
},
};
@malectro
malectro / sense-action-creator-1.js
Last active May 23, 2017 19:11
Evolution of Sense ActionCreators
const getUser = (userId) => (dispatch, getState) => {
// check if we are currently fetching and return that promise
const fetching = getState().fetching[userId];
if (fetching) {
return fetching;
}
// check if the user is cached
const cacheItem = getState().cache[userId];
if (cacheItem && cacheItem.expireTime > Date.now()) {