Skip to content

Instantly share code, notes, and snippets.

@Dylan0916
Created September 29, 2019 03:13
Show Gist options
  • Save Dylan0916/7d1bbbc0ad8ecc763bb7c4fcd1501742 to your computer and use it in GitHub Desktop.
Save Dylan0916/7d1bbbc0ad8ecc763bb7c4fcd1501742 to your computer and use it in GitHub Desktop.
import { Machine, interpret } from 'xstate';
// This machine is completely decoupled from React
export const toggleMachine = Machine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: { TOGGLE: 'active' }
},
active: {
on: { TOGGLE: 'inactive' }
}
}
});
// ======
import { useMachine } from '@xstate/react';
import { toggleMachine } from '../path/to/toggleMachine';
function Toggle() {
const [current, send] = useMachine(toggleMachine);
return (
<button onClick={() => send('TOGGLE')}>
{current.matches('inactive') ? 'Off' : 'On'}
</button>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment