I Wanted to Manage an Array in XState Context
Contents
This is a summary of the unexpected behavior that occurs in XState v5 when you give the Context (state data) an "array" directly.
In XState v5, it seems that even if you assign an array to the Context, the value ends up stored as an object. So it seems safer to wrap it in an object to avoid unexpected behavior.
❌ Don't: context: [] as string[]
✅ Do: context: { items: [] } as { items: string[] }
I created a State Machine whose Context is an array and checked what type it becomes after adding an element with assign.
Inside the assign function, I confirm with logs that it definitely returns an "array".
import { setup, assign } from "xstate";
export const arrayMachine = setup({
types: {
context: [] as string[], // the initial value is an array too
events: {} as { type: "ADD"; item: string },
},
}).createMachine({
id: "arrayMachine",
initial: "active",
context: [],
states: {
active: {
on: {
ADD: {
actions: assign(({ context, event }) => {
// at the start of assign, it is an array
console.log(
"DEBUG: assign initial context:",
context,
"Is Array?",
Array.isArray(context)
);
const newValue = [...context, event.item];
// here it is definitely an array
console.log(
"DEBUG: assign returning:",
newValue,
"Is Array?",
Array.isArray(newValue)
);
return newValue;
}),
},
},
},
},
});
It checks the type of the Context in the initial state and after sending an event.
import { createActor } from "xstate";
import { arrayMachine } from "./arrayMachine";
const actor = createActor(arrayMachine);
actor.start();
console.log("--- Initial State ---");
console.log("Is Array?", Array.isArray(actor.getSnapshot().context));
console.log("\n--- Sending ADD event ---");
actor.send({ type: "ADD", item: "first-item" });
const updatedContext = actor.getSnapshot().context;
console.log("Context value:", updatedContext);
console.log("Is Array?", Array.isArray(updatedContext));
console.log("Constructor:", updatedContext.constructor.name);
Even though assign returns an array, the updated Context was converted into an object.
--- Initial State ---
Context value: []
Is Array? true
--- Sending ADD event ---
DEBUG: assign initial context: [] Is Array? true
DEBUG: assign returning: [ 'first-item' ] Is Array? true
Context value: { '0': 'first-item' }
Is Array? false
Constructor: Object
In the initial state it was [] (Array), but once assign runs, it changes into { '0': 'first-item' }, an object keyed by index. As a result, array methods such as map and filter can no longer be used, which causes runtime errors.
The implementation of the assign action in XState v5 has a step that forcibly merges the context as an object (shallow merge).
The source code on GitHub (packages/core/src/actions/assign.ts) is implemented like this.
Source: statelyai/xstate - assign.ts
// assign.ts (excerpt)
const updatedContext = Object.assign({}, snapshot.context, partialUpdate);
- An empty object
{}is passed as the first argument, andsnapshot.context(the current context) as the second. - Even if
snapshot.contextis the array['a', 'b'],Object.assign({}, ['a', 'b'])is executed. - Per the JavaScript spec, this produces the object
{ '0': 'a', '1': 'b' }.
→ No matter how carefully you implement it to return an "array", the library's internal implementation forcibly converts it into an object. That seems to be how XState v5 works.
The safe choice is to always make the Context an object and hold the array as one of its properties.
const listMachine = setup({
types: {
// hold the array as a property
context: {} as { items: string[] },
},
}).createMachine({
context: { items: [] },
on: {
ADD: {
actions: assign(({ context, event }) => ({
// this way only the items property is updated
items: [...context.items, event.item],
})),
},
},
});
This way context.items always stays an array.
When handling lists in XState, don't cut corners. Wrap them in an object.
I asked about this in GitHub Discussions on the official XState repository and got an answer from a maintainer.
Summary of the answer:
In XState v5, the Context is always expected to be an object→ the assign action converting an array into an object is by design, not a bug
→ I opened a PR, and it is now stated explicitly in the official docs. https://stately.ai/docs/context
![XState docs callout: "The context must be an object. If you need to store a list of items, wrap it in an object, e.g., context: { items: [] }."](/_astro/image-01.CmMA3iwm_Z22PHMk.webp)
Translated from the Japanese original.
Thanks. I'll look into it.
Sorry, that didn't go through. Please try again later.