-
-
Save drcmda/758232aef5e61540c5457980947c3343 to your computer and use it in GitHub Desktop.
Redux thunk example
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'; | |
import _ from 'lodash'; | |
// these types describe what i can do | |
const types = { | |
fetch: "ACTION_ADD", | |
remove: "ACTION_REMOVE" | |
} | |
const actions = { | |
fetch: (url, id) => ( | |
// i'm a "thunk", a function that recives a dispatcher, | |
// i can use it whenever i like to | |
async (dispatch) => { | |
let result = await fetch(url); | |
let json = await result.json(); | |
// now i'll drop my action | |
dispatch({ type: types.fetch, payload: { id, json } }) | |
} | |
), | |
// i'm a regular action, someone can dispatch me | |
remove: (id) => ({ type: types.remove, payload: id }) | |
} | |
// i'm the "reducer", i sort through commands and create states | |
const reducer = (state = {}, { type, payload }) => { | |
switch (type) { | |
// someone requested a url fetch, this is the result, it gets stored under its given key | |
case types.fetch: return { ...state, [payload.id]: payload.json } | |
// a stored object needs to go | |
case types.remove: return _.omit(state, payload); | |
} | |
return state; | |
} | |
const app = async () => { | |
// Create store, contains one single reducer | |
const store = createStore(reducer, applyMiddleware(thunk)); | |
console.log(store.getState()); // {} | |
await store.dispatch(actions.fetch('https://jsonplaceholder.typicode.com/posts', 'testKey')); | |
console.log(store.getState()); // testKey: array[100] | |
store.dispatch(actions.remove('testKey')); | |
console.log(store.getState()); // {} | |
} | |
app(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment