Skip to content

Instantly share code, notes, and snippets.

@drcmda
Last active November 15, 2017 09:41
Show Gist options
  • Save drcmda/758232aef5e61540c5457980947c3343 to your computer and use it in GitHub Desktop.
Save drcmda/758232aef5e61540c5457980947c3343 to your computer and use it in GitHub Desktop.
Redux thunk example
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