Last active
September 15, 2017 04:21
-
-
Save DobrinGanev/1dbc5939fee6e91c5ed3079d0b067bad to your computer and use it in GitHub Desktop.
thunks and redux
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
import { createStore, applyMiddleware } from 'redux' | |
import thunk from 'redux-thunk'; | |
function reducer(state, action) { | |
if (typeof state === 'undefined') { | |
return 0 | |
} | |
switch (action.type) { | |
case 'INCREMENT': | |
return state + 1 | |
case 'DECREMENT': | |
return state - 1 | |
default: | |
return state | |
} | |
} | |
const api = { | |
someMethod: (state) => console.log(state) | |
} | |
const store = createStore( | |
reducer, | |
applyMiddleware(thunk.withExtraArgument(api)) // api as the extra argument | |
) | |
const asyncAction = (action) => { | |
return (dispatch, getState, api) => { // api available | |
dispatch(action) | |
setTimeout(() => { | |
api.someMethod(getState()) | |
}, 3000) | |
} | |
} | |
store.dispatch(asyncAction({ type: 'INCREMENT' })) | |
//------------------thunks -----------------// | |
const add = (x, y) => x + y | |
const simpleThunk = () => add(1, 2) | |
console.log(simpleThunk()) | |
// async thunks | |
const addAsync = (x, y, callback) => { | |
setTimeout(() => { callback(x + y) }, 1000) | |
} | |
const asyncThunk = (callback) => addAsync(10, 15, callback) | |
asyncThunk(res => console.log(res)) | |
const addAsync2 = (x, y) => (callback) => { | |
setTimeout(() => { callback(x + y) }, 1000) | |
} | |
const asyncThunk2 = (callback) => addAsync2(10, 15)(callback) | |
asyncThunk2(res => console.log(res)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment