{"action":"created","issue":{"url":"https://api.github.com/repos/reactjs/redux/issues/533","repository_url":"https://api.github.com/repos/reactjs/redux","labels_url":"https://api.github.com/repos/reactjs/redux/issues/533/labels{/name}","comments_url":"https://api.github.com/repos/reactjs/redux/issues/533/comments","events_url":"https://api.github.com/repos/reactjs/redux/issues/533/events","html_url":"https://github.com/reactjs/redux/issues/533","id":101177265,"number":533,"title":"Simpler introduction to async action creators","user":{"login":"danmaz74","id":302674,"avatar_url":"https://avatars.githubusercontent.com/u/302674?v=3","gravatar_id":"","url":"https://api.github.com/users/danmaz74","html_url":"https://github.com/danmaz74","followers_url":"https://api.github.com/users/danmaz74/followers","following_url":"https://api.github.com/users/danmaz74/following{/other_user}","gists_url":"https://api.github.com/users/danmaz74/gists{/gist_id}","starred_url":"https://api.github.com/users/danmaz74/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/danmaz74/subscriptions","organizations_url":"https://api.github.com/users/danmaz74/orgs","repos_url":"https://api.github.com/users/danmaz74/repos","events_url":"https://api.github.com/users/danmaz74/events{/privacy}","received_events_url":"https://api.github.com/users/danmaz74/received_events","type":"User","site_admin":false},"labels":[{"url":"https://api.github.com/repos/reactjs/redux/labels/docs","name":"docs","color":"5319e7"}],"state":"closed","locked":false,"assignee":null,"milestone":null,"comments":14,"created_at":"2015-08-15T13:41:53Z","updated_at":"2016-02-25T07:38:13Z","closed_at":"2015-09-04T19:52:51Z","body":"I asked someone from my team to study the docs about async actions, and he found them very hard to follow. This confirmed my idea that there should be a simpler introduction about this fundamental aspect of using Redux before going into all the details about middleware, how it works etc.\r\n\r\nI think a good approach could be to add one last chapter to the \"Basics\" part of the docs, with a practical explanation about using async. To explain it to my team member I used a simple example, and now decided to write it down in a way that could be used as the base for this new chapter; you can find it below - it's not 100% polished (and not actually tested) because I'm not sure you'll want to use it. If not interested let me know, and I'll recycle it as a blog post :)\r\n\r\n# Adding async actions ##\r\n\r\nIn Redux, basic action creators are pure functions with no side effects. This means that they can't directly execute any async code, as the Flux architecture instead suggests, because async code has side effects by definition.\r\n\r\nFortunately, Redux comes with a powerful middleware system and one specific middleware library, redux-thunk, that allows us to integrate async calls into our action creators in a clean and easy way. This is just a short practical introduction, but you can learn the full story here [link to Advanced chapter].\r\n\r\nFirst of all, we need to integrate the redux-thunk middleware into our store. We can do this in our Todo List example by changing some lines inside index.js; from this:\r\n\r\n```js\r\nimport React from 'react';\r\nimport { createStore } from 'redux';\r\nimport { Provider } from 'react-redux';\r\nimport App from './containers/App';\r\nimport todoApp from './reducers';\r\n\r\nlet store = createStore(todoApp);\r\n```\r\n\r\nTo this:\r\n\r\n```js\r\nimport React from 'react';\r\nimport { createStore, applyMiddleware } from 'redux';\r\nimport thunk from 'redux-thunk';\r\nimport { Provider } from 'react-redux';\r\nimport App from './containers/App';\r\nimport todoApp from './reducers';\r\n\r\nlet store =  applyMiddleware(thunk)(createStore)(todoApp);\r\n```\r\n\r\nBefore this change, store.dispatch could only accept a simple Action object. With redux-thunk, dispatch can also accept a [thunk function](https://en.wikipedia.org/wiki/Thunk). \r\n\r\n - If dispatch receives an Action object, redux-thunk will do nothing, and the reducers will get called with the action as usual, and change the state synchronously.\r\n - If instead dispatch receives a thunk function, redux-thunk will execute it. It will be the thunk function's responsibility to actually dispatch an action object. More importantly, the thunk function doesn't need to be pure, so it can contain async calls, and can dispatch some (synchronous) action only after the async call has finished, also using the data received from the call. Let's see this with a simple example for our Todo app.\r\n\r\nIn a real app, we'll want to keep our Todo list synchronized with our server. For now we'll only focus on the addTodo action creator; the current one will only update the client side state, but instead we want it to:\r\n\r\n - Optimistically update the local state and UI\r\n - Send the data to the server, so it can update the DB\r\n - Manage the server response\r\n\r\nTo achieve this, we still need our \"optimistic\" addTodo action creator, but we also need an async thunk action creator to handle the whole async process. To keep the changes to the code at a minimum, we'll rename the optimistic action creator, but not the action type that is sent to the reducers (and used in the switch statement to act). This goes into actions.js:\r\n\r\n```js\r\n// renamed optimistic action creator - this won't be called directly \r\n// by the React components anymore, but from our async thunk function\r\nexport function addTodoOptimistic(text) {\r\n  return { type: ADD_TODO, text };\r\n}\r\n\r\n// the async action creator uses the name of the old action creator, so \r\n// it will get called by the existing code when a new todo item should \r\n//  be added\r\nexport function addTodo(text) {\r\n  // we return a thunk function, not an action object!\r\n  // the thunk function needs to dispatch some actions to change the \r\n  // Store status, so it receives the \"dispatch\" function as its first parameter\r\n  return function(dispatch) {\r\n    // here starts the code that actually gets executed when the addTodo action \r\n    // creator is dispatched\r\n    \r\n    // first of all, let's do the optimistic UI update - we need to \r\n    // dispatch the old synchronous action object, using the renamed \r\n    // action creator\r\n    dispatch(addTodoOptimistic(text));\r\n    \r\n    // now that the Store has been notified of the new todo item, we \r\n    // should also notify our server - we'll use here ES6 fetch function \r\n    // to post the data\r\n    fetch('/add_todo', {\r\n\t  method: 'post',\r\n\t  body: JSON.stringify({\r\n\t\ttext\r\n\t  })\r\n    }).then(response => {\r\n\t  // you should probably get a real id for your new todo item here, \r\n\t  // and update your store, but we'll leave that to you\r\n    }).catch(err => {\r\n\t// Error: handle it the way you like, undoing the optimistic update,\r\n\t//  showing a \"out of sync\" message, etc.\r\n    });\r\n  // what you return here gets returned by the dispatch function that used   \r\n  // this action creator\r\n  return null; \r\n  }\r\n}\r\n```\r\n\r\nThe above code and its comments show how you can do async calls, mixing them with optimistic updates, while still using the same old dispatch syntax with an action creator. The action creator itself is still a pure function, but the thunk function it returns doesn't need to be, and it can do our async calls. If needed, the thunk can also access the current store state, as it gets getState as its second argument: `return function(dispatch, getState) { ...`\r\n\r\nRedux-thunk is only one example of what middleware can do; to learn more, proceed to the advanced tutorial [link]"},"comment":{"url":"https://api.github.com/repos/reactjs/redux/issues/comments/188654975","html_url":"https://github.com/reactjs/redux/issues/533#issuecomment-188654975","issue_url":"https://api.github.com/repos/reactjs/redux/issues/533","id":188654975,"user":{"login":"Tjorriemorrie","id":1099093,"avatar_url":"https://avatars.githubusercontent.com/u/1099093?v=3","gravatar_id":"","url":"https://api.github.com/users/Tjorriemorrie","html_url":"https://github.com/Tjorriemorrie","followers_url":"https://api.github.com/users/Tjorriemorrie/followers","following_url":"https://api.github.com/users/Tjorriemorrie/following{/other_user}","gists_url":"https://api.github.com/users/Tjorriemorrie/gists{/gist_id}","starred_url":"https://api.github.com/users/Tjorriemorrie/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/Tjorriemorrie/subscriptions","organizations_url":"https://api.github.com/users/Tjorriemorrie/orgs","repos_url":"https://api.github.com/users/Tjorriemorrie/repos","events_url":"https://api.github.com/users/Tjorriemorrie/events{/privacy}","received_events_url":"https://api.github.com/users/Tjorriemorrie/received_events","type":"User","site_admin":false},"created_at":"2016-02-25T07:38:13Z","updated_at":"2016-02-25T07:38:13Z","body":"Thanks for answering. I'm still not a 100% sure how to structure this, e.g.\r\n\r\nI have an input which I want to persist in the store.\r\nAs the user types, I wish to fetch autocomplete suggestions from a server.\r\n\r\nHow do you suggest I do that? As I have to store the input first, then fetch suggestions. Considering I assume from your response that I need to dispatch the async from the container on input changed, but the container is generated by connect() - there's no props/store? Do I need to dispatch two actions on the handler, e.g.?\r\n\r\n```\r\nconst mapDispatchToProps = (dispatch) => {\r\n    return {\r\n        onChange: (text, place) => {\r\n            dispatch(changeAddress(text, place))\r\n            dispatch(fetchSuggestions(text)                 <--\r\n        }\r\n    }\r\n};\r\n```\r\n\r\nif that is the case, does that mean that you cannot chain actions (or create _reactions_ (Except for when you use async middleware))?"}}