createAction
Generates an action creator for a specific action type.
1
// JavaScript
2
3
function createAction(type)
Copied!
1
// TypeScript
2
3
function createAction<T extends string | symbol | number>(
4
type: T
5
): BasicActionCreator<T>
Copied!

Details

createAction takes an action type value and returns an action creator which produces actions of that type.
For a version of the action creator which accepts a payload value and attaches the returned action, call the withPayload() method (e.g., createAction("…").withPayload().)
In addition to withPayload(), action creators returned by createAction() have the following properties:
  • type: The type value passed to createAction(). Removes the need for a separate action type constant, and allows other helpers such as onAction to inspect the type value of the produced actions at runtime.
  • matches(action): A method that returns true the the passed action has the same type as the ones produced by the action creator.

TypeScript Notes

  • .withPayload() is defined with a type parameter that specifies the payload type. You can override the default (any) by specifying the type parameter explicitly:
    1
    const incrementBy = createAction('incrementBy').withPayload<number>();
    Copied!
  • .matches() is defined as a type predicate. Using it in a condition allows the TypeScript compiler to narrow the type of passed action to the specific type of action returned by the action creator:
    1
    if (incrementBy.matches(action)) {
    2
    const amount = action.payload
    3
    // Type is inferred to be `number` due to matches()
    4
    }
    Copied!

Examples

Defining a basic action:
1
import { createAction } from 'redux-preboiled'
2
3
const increment = createAction('increment')
4
5
increment()
6
// => { type: 'increment' }
7
8
increment.type
9
// => 'increment'
Copied!
Defining an action with payload:
1
import { createAction } from 'redux-preboiled'
2
3
const multiply = createAction('multiply').withPayload()
4
5
multiply(2)
6
// => { type: 'multiply', payload: 2 }
7
8
multiply.type
9
// => 'multiply'
10
11
multiply.matches({ type: 'multiply', payload: 1 })
12
// => true
13
14
multiply.matches({ type: 'increment' })
15
// => false
Copied!
Specifying the action payload type (TypeScript):
1
import { createAction } from 'redux-preboiled'
2
3
const multiply = createAction('multiply').withPayload<number>()
4
5
multiply(2)
6
// OK
7
8
multiply('2')
9
// ERROR: Argument of type '2' is not assignable to parameter of
10
// type 'number'.
Copied!

See Also