Search code examples
statexstate

Can you match a nested state with string paths in xstate?


From the @xstate/react GitHub repo:

... for hierarchical and parallel machines, the state values will be objects, not strings. In this case, it's better to use state.matches(...)

Which looks like this:

if (current.matches({ loading: 'user' })) {
  return /* ... */;
}

But could you replace { loading: 'user' } with "loading.user"?


Solution

  • Absolutely! At least for the current version of xstate (4.6.7) and @xstate/react (0.8.1), the following if statements are equivalent:

    if (current.matches({ loading: 'user' })) {
      return /* ... */;
    }
    
    if (current.matches("loading.user")) {
      return /* ... */;
    }