Skip to content

Instantly share code, notes, and snippets.

@brigand
Created January 1, 2018 23:22
Show Gist options
  • Save brigand/61e1b5c83f58310ff36cc84bf7cd7a67 to your computer and use it in GitHub Desktop.
Save brigand/61e1b5c83f58310ff36cc84bf7cd7a67 to your computer and use it in GitHub Desktop.
Concept for better reducers, with transparent meta properties for lists and id mappings.
const xtPosts = makeState({
// Give it a name for logs
name: 'xtPosts',
// Specify that we're using lists and byId mappings
// maybe these aren't needed.
list: true,
byId: true,
// Handle some redux actions
actions: {
// First arg is the state wrapper
// second arg is the action payload
// orig is the payload of FETCH_XT_FEED (original action)
FETCH_XT_FEED_SUCCESS: (u, { posts, orig: { userId } }) =>
// Update the list with the name being the first argument,
// and the items being the second argument.
// Usually lists are an array of id strings
// This also sets a meta property for when the list was updated.
u.setList(`postsByUser:${userId}`, posts.map(x => x.id))
// Set the posts in an id:value mapping by returning tuples [id, value]
// Updates the meta property for when the item was updated, and when it was first
// stored.
// We pass null as the first arg because this is nameless mapping.
.setIdPairs(null, posts.map(x => [x.id, x])
// We're no longer loading the list for this user, so set it to being complete
.setListLoading(`postsByUser:${userId}`, false),
// Indicate that we're loading the list. We could also empty the list here with setList
// but in this case we don't want that.
FETCH_XT_FEED: (u, { userId }) => u.setListLoading(`postsByUser:${userId}`, true)),
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment