How to use @xstate/react - 10 common examples

To help you get started, we’ve selected a few @xstate/react examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wonderunit / storyboarder / src / js / xr / src / hooks / ui-manager / index.js View on Github external
//   .map(model => model.id)
    //   .map(getPoseImageFilepathById)
    //   .map(THREE.ImageBitmapLoader.load)

    characterModels
      .map(model => model.id)
      .map(getCharacterImageFilepathById)
      .map(filepath => new THREE.ImageBitmapLoader().load(filepath))

    objectModels
      .map(model => model.id)
      .map(getModelImageFilepathById)
      .map(filepath => new THREE.ImageBitmapLoader().load(filepath))
  }, [])

  const [uiCurrent, uiSend, uiService] = useMachine(
    uiMachine,
    {
      immediate: true,
      actions: {
        onTriggerStart (context, event) {
          let u = event.intersection.uv.x
          let v = event.intersection.uv.y

          let cr = getCanvasRenderer()

          let canvasIntersection = cr.getCanvasIntersection(u, v, true, showHelp)
          if (canvasIntersection) {
            let { id } = canvasIntersection

            if (canvasIntersection.type == 'button') {
              playSound('select')
github gatsbyjs / gatsby / www / src / components / feedback-widget / feedback-widget.js View on Github external
const FeedbackWidget = () => {
  // We’re not going to show this widget if JS is disabled
  if (typeof window === `undefined`) {
    return null
  }

  const widgetTitle = useRef(null)
  const successTitle = useRef(null)
  const errorTitle = useRef(null)
  const toggleButton = useRef(null)
  const [current, send] = useMachine(
    feedbackMachine.withConfig({
      actions: {
        focusWidgetTitle() {
          requestAnimationFrame(() => {
            widgetTitle.current.focus()
          })
        },
        focusSuccessTitle() {
          requestAnimationFrame(() => {
            successTitle.current.focus()
          })
        },
        focusErrorTitle() {
          requestAnimationFrame(() => {
            errorTitle.current.focus()
          })
github coodoo / xstate-examples / _old / fsm-service-2-submachine / src / row.js View on Github external
const Row = props => {

	const { item, onUpdate, onCancel } = props

	const [state, send, service] = useMachine(

		// notice how react functions are hooked into fsm as an action
		WorkerMachine.withConfig(
			{
				actions: {
					notifyProgress: (ctx, e) => {
						onUpdate(ctx)
					},
					notifyCancel: (ctx, e) => {
						onCancel(ctx)
					},
				},
			},
			item,
		),
	)
github DevanB / xstate-examples / trivia-game-react / src / App.tsx View on Github external
function App() {
  const [current, send] = useMachine(machine)

  const renderScreen = () => {
    switch (current.value) {
      case 'welcome':
        return  send('START_QUIZ')} />
      case 'loading':
        return 
      case 'failure':
        return (
           send('RETRY')}
            startOver={() => send('START_OVER')}
          />
        )
      case 'quiz':
        return (
github davidkpiano / xstate / docs / sandboxes / todomvc / Todos.jsx View on Github external
export function Todos() {
  const [state, send] = useMachine(persistedTodosMachine);

  useHashChange(e => {
    send(`SHOW.${window.location.hash.slice(2) || "all"}`);
  });

  const { todos, todo } = state.context;

  const numActiveTodos = todos.filter(todo => !todo.completed).length;
  const allCompleted = todos.length > 0 && numActiveTodos === 0;
  const mark = !allCompleted ? "completed" : "active";
  const markEvent = `MARK.${mark}`;
  const filteredTodos = filterTodos(state, todos);

  return (
    <section data-state="{state.toStrings()}">
      <header></header></section>
github davidkpiano / xstate-react-workshop / src / cheat / App.js View on Github external
export function Feedback({ initialState = 'question' }) {
  const [current, send] = useMachine(Feedback.machine);

  useKeyDown('Escape', () =&gt; send({ type: 'CLOSE' }));

  return ;
}
github kyleshevlin / room-sentiment / src / index.js View on Github external
const Results = () =&gt; {
  const [current, send] = useMachine(resultsMachine)
  const { sentiments } = current.context

  if (current.matches('loading')) {
    return <div>Tabulating results...</div>
  }

  if (current.matches('failure')) {
    return (
      <div>Sorry, there was an error calculating the results. Our bad.</div>
    )
  }

  if (current.matches('success')) {
    return (
      <div>
        <div>The average score is...</div></div>
github isaacplmann / sturdy-uis / src / list / List.tsx View on Github external
function List({
  fetchData,
  sideOfTheForce = SideOfTheForce.Light,
  selectedItem,
  onSelection
}: {
  fetchData: () =&gt; Promise&lt;{ results: { name: string }[] }&gt;;
  selectedItem?: any;
  sideOfTheForce?: SideOfTheForce;
  onSelection?: (selectedItem: any) =&gt; void;
}) {
  const [dataState, sendToDataMachine] = useMachine(fetchMachine, {
    services: {
      fetchData: () =&gt; {
        return fetchData().then(r =&gt; r.results);
      }
    },
    actions: {
      notifyHasData: ctx =&gt; {
        selectionState.context.selectedIndex =
          ctx.results &amp;&amp;
          ctx.results.findIndex(
            item =&gt; selectedItem &amp;&amp; selectedItem.name === item.name
          );
      }
    }
  });
  useEffect(() =&gt; {
github nordnet / ui / src / Molecules / Input / Select / Select.tsx View on Github external
const Select = (props: Props) =&gt; {
  assert(Boolean(props.id), `Input.Select: "id" is required.`);
  assert(
    typeof props.value !== 'undefined' ? typeof props.onChange !== 'undefined' : true,
    `Input.Select: You can't use 'value' prop without onChange. It makes sense only if you want a readonly Input.Select, which is really weird. Don't do that.`,
  );

  const trackContext = React.useContext(TrackingContext);

  const isFirstRender = useIsFirstRender();

  /******      Machine instantiation      ******/
  const machineHandlers = useMachine(SelectMachine, {
    context: {
      label: props.label,
      error: props.error || '',
      success: props.success || false,
      options: props.options,
      selectedItems: [],
      disabled: props.disabled || false,
      open: false,
      itemFocusIdx: null,
      placeholder: props.placeholder || '',
      searchQuery: '',
      extraInfo: props.extraInfo || '',
      multiselect: props.multiselect || false,
      lastNavigationType: null,
      visibleOptions: props.options,
      showSearch: props.showSearch || false,
github coodoo / xstate-examples / _old / fsm-service-1-callback / src / app.js View on Github external
export const Wrap = () =&gt; {
	const [state, send] = useMachine(CompressMachine, { log: true })

	return (
		
			
		
	)
}

@xstate/react

XState tools for React

MIT
Latest version published 1 month ago

Package Health Score

92 / 100
Full package analysis

Popular @xstate/react functions