action-cycle

1.0.6 • Public • Published

Action cycle

Small libary for reducing boilerplate related to action creators. It's provide way to define action creators for actions that includes more than 1 step, specificaly it includes:

start - start action that will be something like GET_DATA
end - GET_DATA_END
success - GET_DATA_SUCCESS
fail - GET_DATA_FAIL

Usage example:

import { make } from "action-cycle";

const getTodos = make("[todos] get", {
  start: (id: number) => ({ id }),
  success: (todos: any[]) => ({ todos })
});

getTodos(1); // {type : '[todos] get', payload: { id: 1 } }

getTodos.type; // [todos] get

getTodos.success(["do staff"]); // {type : '[todos] get success', payload: { todos: ['do staff'] } }

getTodos.success.type; // [todos] get success

// same for getTodos.end & getTodos.fail

// note: for all actions you did't define function you will get creator that returns {type: string; payload: null }

Also you can pass options to make function, or use withOptions to get make function with default options. For now options accepts only postfixes map

import { make, withOptions } from "action-cycle";

make(..., ..., {
	// default options
	postfixes: {
		success: ' success',
		fail: ' fail',
		end: ' end',
	}
})

const makeWithDefaults = withOptions({
	postfixes: {
		success: '_SUCCESS',
		fail: '_FAIL',
		end: '_END',
	}
});

const getTodos = makeWithDefaults('GET_TODOS')

getTodos.success.type // GET_TODOS_SUCCESS

Probably that library will go with some separate solution for async actions like redux-observable or redux-sage

Notes

That library created for use it in my projects, but if you want to use it, improved you are welcome.

Also there is a problem that i had no time to solve. About types for actions creators: i used:

type ArgumentTypes<F extends Function> = F extends (...args: infer A) => any
  ? A
  : never;

that i found on stackoverflow :). But there is little bit ugly display of argument in result functions i mean [string, number], because result function arguments is just ...args : ArgumentTypes. If you have solution for it, suggest it please! Thanks!

Readme

Keywords

none

Package Sidebar

Install

npm i action-cycle

Weekly Downloads

7

Version

1.0.6

License

ISC

Unpacked Size

13.1 kB

Total Files

23

Last publish

Collaborators

  • starvinmelon