From f1cd8b8277e3e7a9b8ac80878668813e627b04d5 Mon Sep 17 00:00:00 2001 From: Todd Kennedy Date: Wed, 20 Jul 2016 18:30:19 -0700 Subject: [PATCH] DOC: Add effects example (#186) Add an example to the effects section to show how an effect might have to do multiple async tasks and to call `done` only when complete. --- README.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/README.md b/README.md index 3804256..230873b 100644 --- a/README.md +++ b/README.md @@ -283,6 +283,27 @@ Examples of effects include: performing (server requests), calling multiple `reducers`, persisting state to [localstorage][localstorage]. +```js +const http = require('choo/http') +const choo = require('choo') +const app = choo() +app.model({ + namespace: 'todos', + state: { items: [] }, + effects: { + addAndSave: (data, state, send, done) => { + http.post('/todo', {body: data.payload, json: true}, (err, res, body) => { + data.payload.id = body.id + send('todos:add', data, done) + }) + } + }, + reducers: { + add: (data, state) => ({ items: state.items.concat(data.payload) }) + } +}) +``` + When an `effect` is done executing, it should call the `done(err, res)` callback. This callback used to communicate when an `effect` is done, handle possible errors and send values back to the caller. You'll probably notice when