Skip to content

Instantly share code, notes, and snippets.

@bradennapier
Last active June 19, 2017 06:34
Show Gist options
  • Save bradennapier/619158312584262c6b70f99701beb3eb to your computer and use it in GitHub Desktop.
Save bradennapier/619158312584262c6b70f99701beb3eb to your computer and use it in GitHub Desktop.
Process Example posts
import { Process } from 'redux-saga-process';
import { put, call } from 'redux-saga/effects';
const build_config = config => ({
reduces: 'posts',
pid: 'posts',
exports: ['actions', 'selectors'],
log: false,
...config,
});
export default function configureAsyncProcess(_config, callback) {
const config = build_config(_config);
class PostsProcess extends Process {
constructor(processID, prev_state, proc) {
super(processID, prev_state, proc);
this.state = {
posts: {},
comments: {},
// prev_state holds the this.state of the previous process that is being
// replaced with this one (hot reloading).
...prev_state,
};
}
*handleLikePost({ type, postID, ...action }) {
// handle the logic to modify the value here, check if the post is
// already liked (to toggle it if needed), possibly store the updated
// data, or dispatch to a server -- which can be done asynchronously
const post = {
...this.state.posts[postID],
liked: !!this.state.posts[postID].liked,
};
yield fork([this, this.updateDatabases], 'update_post', postID, post);
yield put({
type: 'UPDATE_POST',
postID,
post,
});
}
*handleNewPost({ type, ...action }) {
const postID = 'generatedIDHere'
const post = { build: 'your post' }
yield fork([ this, this.uploadNewPost ], postID, post )
yield put({
type: 'UPDATE_POST',
postID,
post
})
}
*processStarts() {
/* On Startup */
}
*processCancels() {
/* When Cancelled or Hot Reloaded */
}
}
PostsProcess.config = {
pid: config.pid,
reduces: config.reduces,
};
PostsProcess.initialState = {
visiblePosts: {},
};
PostsProcess.reducer = {
updatePost: (state, { postID, post }) => ({
...state,
visiblePosts: {
...state.visiblePosts,
[postID]: {
...state.visiblePosts[postID],
...post,
},
},
}),
};
PostsProcess.actionRoutes = {
// when LIKE_POST is dispatched
likePost: 'handleLikePost',
};
PostsProcess.actionCreators = {
// allow components to import likePost('myPostID', { ...post })
// to dispatch { type: 'LIKE_POST', postID: 'myPostID', post: { ...post } }
likePost: ['postID', 'post'],
};
return PostsProcess;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment