Last active
November 6, 2016 00:26
-
-
Save tannerlinsley/19fc8c402d13762ac65fd8be5d670f3d to your computer and use it in GitHub Desktop.
Comparisons between redux-thunks, redux-sagas, and jumpsuit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Thunk | |
import { loading, setAll, error, loading} from 'actions/posts' | |
export refreshPosts () { | |
return (dispatch) => { | |
dispatch(loading(true)) | |
return Axios.get('posts') | |
.then((res) => { | |
dispatch(setAll(res.data)) | |
}) | |
.catch((err) => { | |
dispatch(error('Network Error')) | |
}) | |
.finally(() => { | |
dispatch(loading(false)) | |
}) | |
} | |
} | |
// ------ VS ------- | |
// Jumpstate | |
import Posts from 'state/posts' | |
export refreshPosts () { | |
Posts.loading(true) | |
return Axios.get('posts') | |
.then((res) => { | |
Posts.setAll(res.data) | |
}) | |
.catch((err) => { | |
Posts.error('Network Error') | |
}) | |
.finally(() => { | |
Posts.loading(false) | |
}) | |
} | |
// Saga | |
import { takeEvery, takeLatest } from 'redux-saga' | |
import { call, put } from 'redux-saga/effects' | |
import { loading, setAll, error, loading} from 'actions/posts' | |
export function* refreshPostsSaga() { | |
yield* takeEvery("REFRESH_POSTS", fetchPosts); | |
} | |
function* fetchPosts() { | |
yield put(loading(true)) | |
try { | |
const { data } = yield call(Axios.get, 'posts') | |
yield put(setAll(data)) | |
} catch (e) { | |
yield put(error('Network Error')); | |
} | |
yield put(loading(false)) | |
} | |
// ... | |
dispatch({type: 'REFRESH_POSTS'}) | |
// ----- VS ------- | |
// Jumpsuit Named-Effect | |
import { Effect } from 'jumpsuit' | |
import Posts from 'state/posts' | |
export Effect('REFRESH_POSTS', (payload) => { | |
Posts.loading(true) | |
return Axios.get('posts') | |
.then((res) => { | |
Posts.setAll(res.data) | |
}) | |
.catch((err) => { | |
Posts.error('Network Error') | |
}) | |
.finally(() => { | |
Posts.loading(false) | |
}) | |
}) | |
// ... | |
refreshPosts() | |
// Jumpsuit Generic Side-Effects | |
import { Effect } from 'jumpsuit' | |
import Analytics from 'state/analytics' | |
export Effect((action, getState) => { | |
const { analytics } = getState() | |
if (!analytics.ga) { | |
Analytics.loadGA() | |
} | |
}) | |
// or | |
import { Effect } from 'jumpsuit' | |
import Layout from 'state/layout' | |
export Effect((action, getState) => { | |
const { auth } = getState() | |
if (!auth.status) { | |
Layout.showLogin(true) | |
} | |
}) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment