{"id":19006561,"url":"https://github.com/wellguimaraes/actionware","last_synced_at":"2025-07-08T11:02:35.652Z","repository":{"id":57172827,"uuid":"80164013","full_name":"wellguimaraes/actionware","owner":"wellguimaraes","description":"Redux with less boilerplate, actions statuses and controlled side-effects in a single shot.","archived":false,"fork":false,"pushed_at":"2018-03-15T18:39:20.000Z","size":502,"stargazers_count":200,"open_issues_count":2,"forks_count":7,"subscribers_count":6,"default_branch":"master","last_synced_at":"2024-12-21T04:02:53.431Z","etag":null,"topics":["actions","async-actions","boilerplate","react-redux","redux"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wellguimaraes.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-01-26T22:58:50.000Z","updated_at":"2023-12-31T01:34:59.000Z","dependencies_parsed_at":"2022-08-24T13:21:31.515Z","dependency_job_id":null,"html_url":"https://github.com/wellguimaraes/actionware","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellguimaraes%2Factionware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellguimaraes%2Factionware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellguimaraes%2Factionware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wellguimaraes%2Factionware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wellguimaraes","download_url":"https://codeload.github.com/wellguimaraes/actionware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248675439,"owners_count":21143763,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["actions","async-actions","boilerplate","react-redux","redux"],"created_at":"2024-11-08T18:33:02.692Z","updated_at":"2025-04-13T06:42:15.426Z","avatar_url":"https://github.com/wellguimaraes.png","language":"JavaScript","funding_links":[],"categories":["Marks"],"sub_categories":["[React - A JavaScript library for building user interfaces](http://facebook.github.io/react)"],"readme":"# ![Actionware](assets/logo.png)\n\n[![Build Status](https://travis-ci.org/wellguimaraes/actionware.svg?branch=master)](https://travis-ci.org/wellguimaraes/actionware)\n\n[Redux](http://redux.js.org/) with less boilerplate, actions statuses and controlled side-effects in a single shot. \n\n- no more **action creators** and **action types**, just **actions¹** and **reducers**\n- **actions** dispatch their result automatically\n- **error status** for every action with no extra code\n- **busy status** for every async action (yep, no extra code!)\n- **cancellable** actions\n\n\u003csmall\u003e**¹** With Actionware, **actions** have a different meaning: they're just functions which execution generate events. \nSee [usage](#usage) section to better understand.\u003c/small\u003e\n\n###### Extra power\nWanna have state selectors/getters in a decent way? Use it combined with **[Stateware](https://github.com/wellguimaraes/stateware)** lib.\n\n## Setup\n\n#### Install it\n- Yarn: `yarn add actionware`\n- NPM: `npm i actionware --save`\n\n#### After creating your Redux store, let Actionware know your store instance. Optionally you\ncan define custom action types prefix and suffixes:\n```js\nimport * as actionware from 'actionware';\n\nactionware.setup({\n  store,\n  defaultPrefix, // default: 'actionware:'\n  errorSuffix,   // default: ':error'\n  cancelSuffix,  // default: ':cancel'\n  busySuffix     // default: ':busy'\n});\n```\n\n#### Add actionware reducer to your root reducer:\nTo make Redux store react to **busy** and **error** status changes, \nmake sure you add the Actionware reducer into your root reducer. \n```js\nimport { combineReducers } from 'redux';\nimport { actionwareReducer } from 'actionware';\n\nconst rootReducer = combineReducers({ \n  actionware: actionwareReducer,\n  // your reducers\n});\n```\n\n## Usage\n\n#### Simple actions\n```js\nexport function incrementCounter() { }\n```\n\n#### Async actions\nWhatever you return will be the action payload \n\n```js\n// Note that the store is always the last arg\nexport async function loadUsers(arg1, arg2, argN, store) {\n  const response = await fetch('/my/api/users');\n  return response.json();\n}\n```\n\n#### Invoke any action \nUse `call` to invoke an action and let Actionware handle\nthe execution lifecycle (managing error and busy statuses, notifying listeners, etc).\n```js\nimport { call } from 'actionware';\n\ncall(loadUsers, arg1, arg2, argN);\n```\n\n#### Cancel an action execution\n```js\nimport { call } from 'actionware';\n\nconst actionCall = call(loadUsers, arg1, arg2, argN);\n\nactionCall.cancel()\n```\n\nTo cancel inner calls or other async executions, use `setExtra` inside an async action \nto keep information needed and use them on a cancellation listener:\n```js\nimport { call, onCancel} from 'actionware';\nimport api from './path/to/api';\n\n// Don't use arrow functions here, \n// otherwise a context value can't be set\nexport async function someAction() {\n  const apiCall = api.get('/some/endpoint')\n  const anotherActionCall = call(anotherAction, 'someParam')\n  \n  this.setExtra({ apiCall })\n  this.setExtra({ anotherActionCall }) // you can call it multiple times\n    \n  const apiResponse = await apiCall\n  const anotherResponse = await anotherActionCall\n  \n  // ...\n  \n  return apiResponse.data\n}\n\nexport async function anotherAction() {\n  // ...\n}\n\nonCancel(someAction, ({ extras }) =\u003e {\n  // Check if the action execution is still cancellable\n  if (extras.anotherActionCall.canBeCancelled)\n    extras.anotherActionCall.cancel()\n    \n  // Cancel the api call...\n})\n```\n\n#### Clear action error\n```js\nimport { clearError } from 'actionware'\n\nexport async function someAction() {\n  // ...\n}\n\nclearError(someAction)\n```\n\n#### Reducers:\n```js\nimport { createReducer } from 'actionware';\nimport { loadUsers, persistUser, incrementCounter } from 'path/to/actions';\n\nconst initialState = { users: [], count: 0 };\n\nexport default createReducer(initialState)\n  .on(loadUsers, \n    (state, users) =\u003e ({ ...state, users }))\n  \n  .on(incrementCounter, \n    (state) =\u003e ({ ...state, counter: state.counter + 1 }))\n  \n  // Bind legacy action types\n  .on('OLD_ACTION_TYPE',\n    (state, payload) =\u003e { /* return new state */ })\n  \n  // Bind multiple actions to the same handler    \n  .on(\n    someAction, \n    anotherAction,\n    (state, payload) =\u003e { /* return new state */ })\n  \n  // Actionware handles errors, cancellation and 'before' events,\n  // but if you need to do something else\n  \n  .onError(persistUser, \n    (state, error, ...args) =\u003e { /* return new state */ })\n    \n  .onCancel(loadUsers, \n    (state, extras, ...args) =\u003e { /* return new state */ })\n  \n  .before(loadUsers, \n    (state, ...args) =\u003e { /* return new state */ });\n```\n\n#### Busy and failure statuses for all your actions:\n```js\nimport { getError, isBusy } from 'actionware';\nimport { loadUsers } from 'path/to/userActions';\n\n// Whenever needed...\nisBusy(loadUsers);\ngetError(loadUsers);\n```\n\n#### Use listeners to manage side effects:\nNote that busy listeners are called when busy status changes. \n```js\nimport { onSuccess, onError, onCancel, before, beforeAll } from 'actionware';\nimport { createUser } from 'path/to/actions';\n\n// global success listener\nonSuccess(({ action, args, payload, store }) =\u003e eventTracker.register(action.name));\n\n// per action success listener\nonSuccess(createUser, ({ args, payload, store }) =\u003e history.push(`/users/${user.id}`));\n\n// error listeners\nonError(({ action, args, error }) =\u003e { /* ... */ });\nonError(createUser, ({ args, error }) =\u003e { /* ... */ });\n\n// cancellation listeners\nonCancel(({ action, args, extras }) =\u003e { /* ... */ });\nonCancel(createUser, ({ args, extras }) =\u003e { /* ... */ });\n\n// before listeners \n// NOTE: 'beforeAll' is just an alias for 'before'\nbeforeAll(({ action, args, store}) =\u003e { /* ... */ });\nbefore(createUser, ({ args, store }) =\u003e { /* ... */ });\n```\n\n#### Interaction-dependent flows\nWhen you have \"complex\" flows that depend on some interaction to start or continue,\nyou can use `next` to wait for some action completion in this fashion:\n```js\nimport { call, next } from 'actionware';\nimport { login, showTip, acknowledgeTip } from 'path/to/actions';\n\nexport async function appEducationFlow() {\n  // Wait for the next successful login\n  await next(login); \n  \n  call(showTip, 'headerButtons');\n  await next(acknowledgeTip);\n  \n  history.redirect('/some/route');\n  \n  call(showTip, 'sideMenu');\n  await next(acknowledgeTip);\n}\n\n// At some point, start the flow\nappEducationFlow();\n```\n\n## Usage with React\n \n#### Inject actions and status into components as props\nBy using `withActions` to wrap a component, actions are injected into it as props \nand can be invoked without using `call`. \n```js\nimport * as React from 'react';\nimport { connect } from 'react-redux';\nimport { withActions, isBusy, getError } from 'actionware';\nimport { loadUsers } from 'path/to/actions';\n\nconst actions = { loadUsers };\n\nconst mapStateToProps = ({ company }) =\u003e ({\n  users   : company.users,\n  loading : isBusy(loadUsers),\n  error   : getError(loadUsers)\n});\n\n@connect(mapStateToProps)\n@withActions(actions)\nclass MyConnectedComponent extends Component {\n  componentDidMount() {\n    this.props.loadUsers();    \n  }\n  \n  render() {\n    const { loading, error } = this.props;\n    \n    if (loading) return (\u003cdiv\u003eLoading...\u003c/div\u003e);\n    if (error) return (\u003cdiv\u003eFailed to load users...\u003c/div\u003e);\n    \n    return (\n      \u003cdiv\u003e\n        { users.map(it =\u003e \u003cUser key={it.id} {...it} /\u003e) }\n      \u003c/div\u003e\n    );\n  }\n}\n\nexport default MyConnectedComponent\n```\n\n#### Without injecting actions as props\nIn case you prefer not injecting actions as props into your component, you can use `createActions` this way:\n```js\nimport { createActions } from 'actionware'\n\nconst actions = createActions('optionalPrefix:', {\n  someAction,\n  anotherAction\n})\n\nconst MyComponent = () =\u003e (\n  \u003cdiv\u003e\n    \u003cbutton onClick={ actions.someAction }\u003e\u003c/button\u003e\n  \u003c/div\u003e\n)\n\n```\n\n\n## Testing\n\n#### Mock `call` and `next` functions\nWhile testing, you're able to replace the `call` and `next` functions by custom \nspy/stub to simplify tests.\n```js\nimport { mockCallWith, mockNextWith } from 'actionware';\n\nconst callSpy = sinon.spy();\nconst nextStub = sinon.stub().returns(Promise.resolve());\n\nmockCallWith(callSpy);\nmockNextWith(nextStub);\n\n// Get back to default behavior\nmockCallWith(null); \nmockNextWith(null); \n```\n\n#### Reducers\nFor testing reducers, you can do the following:\n\n```js\nimport { successType } from 'actionware';\nimport { loadUsers } from 'path/to/userActions';\nimport usersReducer from 'path/to/usersReducer';\n\ndescribe('usersReducer', () =\u003e {\n  describe('on loadUsers', () =\u003e {\n    it('should replace the \"users\" array with the loaded users', () =\u003e {\n      const currentState = { users: [ ] }; \n      const loadedUsers = [ 'John Doe', 'Joane Doe', 'Steve Gates' ];\n\n      // Call reducer with currentState and a regular Redux action       \n      const newState = usersReducer(\n        currentState, \n        { type: successType(loadUsers), payload: loadedUsers }\n      );\n      \n      expect(newState.items).to.equals(loadedUsers);\n    });  \n  });\n});\n```\n\n## API\n\n#### Setup  \n- **setup**({ store, defaultPrefix?, errorSuffix?, busySuffix?, cancelSuffix? }): void\n\n#### Most used\n- **withActions**(actions: object): Function(wrappedComponent: Component)\n- **createActions**(actions: object): object\n- **isBusy**(action: Function): bool\n- **getError**(action: Function): object\n- **clearError**(action: Function): void\n- **call**(action: Function, ...args)\n- **next**(action: Function)\n- **createReducer**(initialState: object, handlers: []): Function\n\n#### Listeners\n\n###### Global\n- **onSuccess**(listener: ({ action, payload, args, store }) =\u003e void)\n- **onError**(listener: ({ action, error, args, store }) =\u003e void)\n- **beforeAll**(listener: ({ action, args, store}) =\u003e void)\n\n###### Per action\n- **onSuccess**(action: Function, listener: ({ payload, args, store }) =\u003e void)\n- **onError**(action: Function, listener: ({ error, args, store }) =\u003e void)\n- **before**(action: Function, listener: ({ args, store }) =\u003e void)\n\n#### Test helpers\n- **mockCallWith**(fakeCall: Function)\n- **mockNextWith**(fakeNext: Function)\n- **successType**(action: Function)\n- **errorType**(action: Function)\n- **busyType**(action: Function)\n\n## License\n[MIT](LICENSE) \u0026copy; Wellington Guimaraes\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwellguimaraes%2Factionware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwellguimaraes%2Factionware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwellguimaraes%2Factionware/lists"}