How to display the current state (string) #5268
-
How to display the current state's name as a string?This might be a dumb question, but I only found ways to check that a current state is equal to a value: // state.value === 'question'
state.matches('question'); // true But I haven't found a way to get an actual string. For instance I would like to render and display the current state in React: return <h1>Current state: {state.value}</h1> // ❌ `value` is not a string |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The state value can be a string or an object. If you have a flat state machine (no nested states, then One such way is this: https://stately.ai/docs/migration#the-statetostrings-method-has-been-removed import { type StateValue } from 'xstate';
export function getStateValueStrings(stateValue: StateValue): string[] {
if (typeof stateValue === 'string') {
return [stateValue];
}
const valueKeys = Object.keys(stateValue);
return valueKeys.concat(
...valueKeys.map((key) =>
getStateValueStrings(stateValue[key]!).map((s) => key + '.' + s),
),
);
}
// ...
const stateValueStrings = getStateValueStrings(stateValue);
// e.g. ['green', 'yellow', 'red', 'red.walk', 'red.wait', …] |
Beta Was this translation helpful? Give feedback.
The state value can be a string or an object. If you have a flat state machine (no nested states, then
state.value
is a string. Otherwise, it's an object and it's up to you to display that as a string however you see fit.One such way is this: https://stately.ai/docs/migration#the-statetostrings-method-has-been-removed