Skip to main content

Standard and Standalone Actions

Standalone Actions

Sometimes you might need to define a "model" action but without an associated model. Say for example that you need an array swap method that needs to be processed by middlewares (e.g. undoMiddleware). One way to achieve this is to use standalone actions like this:

const arraySwap = standaloneAction(
"myApp/arraySwap",
<T>(array: T[], index1: number, index2: number): void => {
if (index2 < index1) {
;[index1, index2] = [index2, index1]
}
// since a same node cannot be in two places at once we will remove
// both then reinsert them
const [v1] = array.splice(index1, 1)
const [v2] = array.splice(index2 - 1, 1)
array.splice(index1, 0, v2)
array.splice(index2, 0, v1)
}
)

Note the following prerequisites apply to standalone actions:

  • The name provided must be unique across your whole application.
  • The first argument (the target) must always be an existing tree node.

Standard Actions

In order to work over objects and arrays without requiring declaring custom actions you can use the already predefined objectActions and arrayActions (note these also work over class models).

objectActions work over any kinds of objects (including models themselves) and offer:

  • set(obj, key, value) to set a key.
  • delete(obj, key) to delete a key.
  • assign(obj, partialObj) to assign values (similar to Object.assign).
  • call(methodName, ...args) to call a method.

arrayActions work over arrays and offer:

  • set(array, index, value) to set an index.
  • delete(array, index) to delete an index.
  • setLength(array, length) to set a new length.
  • swap(array, index1, index2) to swap two array elements.

Plus the usual array mutation methods (pop, push, etc.).