{"_id":"@akiellor/redux-loop","_rev":"3-91b7b219c71ee5e6a90d9c7686917293","name":"@akiellor/redux-loop","description":"Sequence your effects naturally and purely by returning them from your reducers.","dist-tags":{"latest":"2.1.1"},"versions":{"2.1.1":{"name":"@akiellor/redux-loop","npmName":"redux-loop","version":"2.1.1","description":"Sequence your effects naturally and purely by returning them from your reducers.","main":"lib/index.js","jsnext:main":"modules/index.js","homepage":"https://github.com/RaiseMarketplace/redux-loop","repository":{"type":"git","url":"git+https://github.com/RaiseMarketplace/redux-loop.git"},"bugs":{"url":"https://github.com/RaiseMarketplace/redux-loop/issues"},"peerDependencies":{"redux":"^3.0.0"},"files":["modules","lib"],"scripts":{"clean":"rimraf lib","build":"babel modules --out-dir lib","test":"tape -r babel-polyfill -r babel-register './test/*.test.js'","prepublish":"npm run clean && npm run build"},"keywords":["redux","middleware","effects","side effects","elm","loop"],"tags":["redux","middleware","effects","side effects","elm","loop"],"author":{"name":"Luke William Westby","email":"luke.westby@raise.com"},"license":"MIT","devDependencies":{"babel":"6.3.13","babel-cli":"6.3.17","babel-plugin-transform-es3-member-expression-literals":"6.3.13","babel-plugin-transform-es3-property-literals":"6.3.13","babel-plugin-transform-object-rest-spread":"6.3.13","babel-polyfill":"6.7.2","babel-preset-es2015":"6.3.13","babel-register":"6.7.2","immutable":"^3.7.6","redux":"3.0.5","rimraf":"2.4.4","tape":"4.5.1"},"gitHead":"30d8937dad837622e0a5e76fd4b58a6838a17053","_id":"@akiellor/redux-loop@2.1.1","_shasum":"82fc02f76f68ed5c8cad0c13d6aca9daf4c53188","_from":".","_npmVersion":"3.3.12","_nodeVersion":"5.4.0","_npmUser":{"name":"akiellor","email":"akiellor@gmail.com"},"dist":{"shasum":"82fc02f76f68ed5c8cad0c13d6aca9daf4c53188","tarball":"https://registry.npmjs.org/@akiellor/redux-loop/-/redux-loop-2.1.1.tgz","integrity":"sha512-05LdEf7UK3YxDwLwu4kvSGvE1pchR4EhyyIOnVwxQvtT2RA0pBSlGW60AvsAKZvCbbZhoyR/0zsTNnzLi7KQnw==","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEYCIQC2wXhV8oQ041I53p1RyorQQzzi74ZUNi2KioZz7GQ+cAIhAJmABG+e3lMGgOsh5UzOLhDutKVMBEbvfvIhnd770/RS"}]},"maintainers":[{"name":"akiellor","email":"akiellor@gmail.com"}],"_npmOperationalInternal":{"host":"packages-12-west.internal.npmjs.com","tmp":"tmp/redux-loop-2.1.1.tgz_1466050672559_0.9405596873257309"}}},"readme":"# redux-loop\n\n[![Build Status](https://travis-ci.org/raisemarketplace/redux-loop.svg?branch=master)](https://travis-ci.org/raisemarketplace/redux-loop)\n\n\nA port of [elm-effects](https://github.com/evancz/elm-effects) and the [Elm\nArchitecture](https://github.com/evancz/elm-architecture-tutorial) to Redux\nthat allows you to sequence your effects naturally and purely by returning them\nfrom your reducers.\n\n> Isn't it incorrect to cause side-effects in a reducer?\n\nYes! Absolutely.\n\n> Doesn't redux-loop put side-effects in the reducer?\n\nIt doesn't. The values returned from the reducer when scheduling an effect with\nredux-loop only _describe_ the effect. Calling the reducer will not cause the\neffect to run. The value returned by the reducer is just an object that the\nstore knows how to interpret when it is enhanced by redux-loop. You can safely\ncall a reducer in your tests without worrying about waiting for effects to finish\nand what they will do to your environment.\n\n> What are the environment requirements for redux-loop?\n\n`redux-loop` requires polyfills for ES6 `Promise` and `Symbol` to be included if\nthe browsers you target don't natively support them.\n\n## Quick Example\n\n```javascript\nimport { createStore } from 'redux';\nimport { install, loop, Effects } from 'redux-loop';\nimport { fromJS } from 'immutable';\n\nconst firstAction = {\n  type: 'FIRST_ACTION',\n};\n\nconst doSecondAction = (value) => {\n  return new Promise((resolve) => {\n    setTimeout(() => {\n      resolve({\n        type: 'SECOND_ACTION',\n        payload: value,\n      });\n    });\n  });\n}\n\nconst thirdAction = {\n  type: 'THIRD_ACTION',\n};\n\n// immutable store state allowed by default, but not required\nconst initialState = fromJS({\n  firstRun: false,\n  secondRun: false,\n  thirdRun: false,\n});\n\nfunction reducer(state, action) {\n  switch(action.type) {\n\n  case 'FIRST_ACTION':\n    // Enter a sequence at FIRST_ACTION, SECOND_ACTION and THIRD_ACTION will be\n    // dispatched in the order they are passed to batch\n    return loop(\n      state.set('firstRun', true),\n      Effects.batch([\n        Effects.promise(doSecondAction, 'hello'),\n        Effects.constant(thirdAction)\n      ])\n    );\n\n  case 'SECOND_ACTION':\n    return state.set('secondRun', action.payload);\n\n  case 'THIRD_ACTION':\n    return state.set('thirdRun', true);\n\n  default:\n    return state;\n  }\n}\n\n// Note: passing enhancer as the last argument to createStore requires redux@>=3.1.0\nconst store = createStore(reducer, initialState, install());\n\nstore\n  .dispatch(firstAction)\n  .then(() => {\n    // dispatch returns a promise for when the current sequence is complete\n    // { firstRun: true, secondRun: 'hello', thirdRun: true }\n    console.log(store.getState().toJS());\n  });\n```\n\n## Why use this?\n\nHaving used and followed the progression of Redux and the Elm Architecture, and\nafter trying other effect patterns for Redux, we came to the following\nconclusion:\n\n> Synchronous state transitions caused by returning a new state from the reducer\n> in response to an action are just one of all possible effects an action can\n> have on application state.\n\nMany other methods for handling effects in Redux, especially those implemented\nwith action-creators, incorrectly teach the user that asynchronous effects are\nfundamentally different from synchronous state transitions. This separation\nencourages divergent and increasingly specific means of processing particular\ntypes effects. Instead, we should focus on making our reducers powerful enough\nto handle asynchronous effects as well as synchronous state transitions. With\n`redux-loop`, the reducer doesn't just decide what happens _*now*_ due to a\nparticular action, it decides what happens _*next*_. All of the behavior of your\napplication can be traced through one place, and that behavior can be easily broken\napart and composed back together. This is one of the most powerful features of the\n[Elm architecture](https://github.com/evancz/elm-architecture-tutorial), and with\n`redux-loop` it is a feature of Redux as well.\n\n## Tutorial\n\n### Install the store enhancer\n\n```javascript\nimport { createStore, compose, applyMiddleware } from 'redux';\nimport reducer from './reducers';\nimport { install } from 'redux-loop';\nimport someMiddleware from 'some-middleware';\n\nconst enhancer = compose(\n  applyMiddleware(someMiddleware),\n  install()\n);\n\n// Note: passing enhancer as the last argument to createStore requires redux@>=3.1.0\nconst store = createStore(reducer, initialState, enhancer);\n```\n\nInstalling `redux-loop` is as easy as installing any other store enhancer. You\ncan apply it directly over `createStore` or compose it with other enhancers\nand middlewares. Composition of enhancers can be confusing, so the order in\nwhich `install()` is applied may matter. If something like `applyMiddleware()`\ndoesn't work when called before `install()`, applying after may fix the issue.\n\n### Write a reducer with some effects\n\n```javascript\nimport { Effects, loop } from 'redux-loop';\nimport { loadingStart, loadingSuccess, loadingFailure } from './actions';\n\nexport function fetchDetails(id) {\n  return fetch(`/api/details/${id}`)\n    .then((r) => r.json())\n    .then(loadingSuccess)\n    .catch(loadingFailure);\n}\n\nexport default function reducer(state, action) {\n  switch (action.type) {\n    case 'LOADING_START':\n      return loop(\n        { ...state, loading: true },\n        Effects.promise(fetchDetails, action.payload.id)\n      );\n\n    case 'LOADING_SUCCESS':\n      return {\n        ...state,\n        loading: false,\n        details: action.payload\n      };\n\n    case 'LOADING_FAILURE':\n      return {\n        ...state,\n        loading: false,\n        error: action.payload.message\n      };\n\n    default:\n      return state;\n  }\n}\n```\n\nAny reducer case can return a `loop` instead of a state object. A `loop` joins\nan updated model state with an effect for the store to process. There are\nseveral options for effects, all available under the `Effects` object:\n\n- `promise(factory, ...args)`\n  - Accepts a `factory` function that returns a `Promise` for an action\n    instance when called with `args`.\n- `constant(action)`\n  - Accepts an `action` instance to dispatch immediately once the current\n    dispatch cycle is completed.\n- `batch(effects)`\n  - Accepts an array of other effects and runs them in parallel, dispatching\n    the resulting actions once all effects are resolved.\n- `none()`\n  - A no-op action, for convenience when writing custom effect creators\n\n### Easily test reducer results\n\n```javascript\nimport test from 'tape';\nimport reducer, { fetchDetails } from './reducer';\nimport { loadingStart } from './actions';\nimport { Effects, loop } from 'redux-loop';\n\ntest('reducer works as expected', (t) => {\n  const state = { loading: false };\n\n  const result = reducer(state, loadingStart(1));\n\n  t.deepEqual(result, loop(\n    { loading: true },\n    Effects.promise(fetchDetails, 1)\n  ));\n});\n```\n\nEffects are declarative specifications of the next behavior of the store. They\nare only processed by an active store, pushing effecting behavior to the edge of\nthe application. You can call a reducer as many times with a given action and\nstate and always get a result which is `deepEqual`.\n\n> CAVEAT\n> For testing sanity, always pass a referenceable function to `Effects.promise`.\n> Functions curried or bound from the same function with the same arguments are\n> not equal within JavaScript, and so are best to avoid if you want to compare\n> effects in your tests.\n\n### Use the custom `combineReducers` if you need it\n\n```javascript\nimport { createStore } from 'redux';\nimport { combineReducers, install } from 'redux-loop';\n\nimport { firstReducer, secondReducer } from './reducers';\n\nconst reducer = combineReducers({\n  first: firstReducer,\n  second: secondReducer,\n});\n\n// Note: passing enhancer as the last argument to createStore requires redux@>=3.1.0\nconst store = createStore(reducer, initialState, install());\n```\n\nThe `combineReducers` implementation in `redux-loop` is aware that some of\nyour reducers might return effects, and it knows how to properly compose them\nand forward them to the store. The built-in `createStore` in `redux` will not\nproperly identify effects from your nested reducers' results and execute them,\nand the `redux-loop` implementation is completely compatible with the behavior\nof the built-in version so there should be no problem with exchanging it.\n\n#### Using redux-loop's `combineReducers` with Immutable.js (or any other data structure)\n\n```javascript\nimport { combineReducers } from 'redux-loop';\nimport { Map } from 'immutable';\n\nimport { firstReducer, secondReducer } from './reducers';\n\nconst reducers = {\n  first: firstReducer,\n  second: secondReducer,\n}\n\n//Map() is now used as the new root state, and custom accessor and mutator properties are provided\nconst reducer = combineReducers(\n    reducers,\n    Map(),\n    (child, key) => child.get(key),\n    (child, key, value) => child.set(key, value)\n);\n\n```\n\nOur `combineReducers` can also handle states made of data structures\nother than the default `{}`, you simply pass it in the root state,\nan accessor function (which returns a value for that key), and a mutator\nfunction (which returns a **new version** of the object with a value\nset at a given key). The example above demonstrates using Immutable.js'\nMap() data structure, but you can use any `key => value` data structure\nas long as you provide your own accessor and mutator functions.\n\n### Avoid circular loops!\n\n```javascript\nfunction reducer(state, action) {\n  switch (action.type) {\n    case 'FIRST':\n      return loop(\n        state,\n        Effects.constant(second())\n      );\n\n    case 'SECOND':\n      return loop(\n        state,\n        Effects.constant(first())\n      );\n  }\n}\n```\n\nThis minimal example will cause perpetual dispatching! While it is also possible\nto make this mistake with large, complicated networks of `redux-thunk` action\ncreators, it is much easier to spot the mistake before it is made. It helps to\nkeep your reducers small and focused, and use `combineReducers` or manually\ncompose reducers so that the number of actions you deal with at one time is\nsmall. A small set of actions which initiate a `loop` will help reduce the\nlikelihood of causing circular dispatches.\n\n## Support\n\nPotential bugs, generally discussion, and proposals or RFCs should be submitted\nas issues to this repo, we'll do our best to address them quickly. We use this\nlibrary as well and want it to be the best it can! For questions about using the\nlibrary, [submit questions on StackOverflow](http://stackoverflow.com/questions/ask)\nwith the [`redux-loop` tag](http://stackoverflow.com/questions/tagged/redux-loop).\n\n### Don't see a feature you want?\n\nIf you're interested in adding something to `redux-loop` but don't want to wait\nfor us to incorporate the idea you can follow these steps to get your own installable\nversion of `redux-loop` with your feature included:\n\n1. Fork the main repo here\n1. Add your feature or change\n1. Change the package `\"name\"` in package.json to be `\"@<your-npm-username>/redux-loop`\n1. Commit to master and `npm publish`\n1. `npm install @<your-npm-username>/redux-loop`\n\nWe are _**always**_ interested in new ideas, but sometimes we get a little busy and fall\nbehind on responding and reviewing PRs. Hopefully this process will allow you to\ncontinue making progress on your projects and also provide us with more context if and\nwhen you do decide to make a PR for your new feature or change. The best way to verify\nnew features for a library is to use them in real-world scenarios!\n\n## Contributing\n\nPlease note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. Multiple language translations are available at [contributor-covenant.org](http://contributor-covenant.org/version/1/3/0/i18n/)\n","maintainers":[{"name":"akiellor","email":"akiellor@gmail.com"}],"time":{"modified":"2022-06-12T14:27:00.444Z","created":"2016-06-16T04:17:53.034Z","2.1.1":"2016-06-16T04:17:53.034Z"},"homepage":"https://github.com/RaiseMarketplace/redux-loop","keywords":["redux","middleware","effects","side effects","elm","loop"],"repository":{"type":"git","url":"git+https://github.com/RaiseMarketplace/redux-loop.git"},"author":{"name":"Luke William Westby","email":"luke.westby@raise.com"},"bugs":{"url":"https://github.com/RaiseMarketplace/redux-loop/issues"},"license":"MIT","readmeFilename":"README.md"}