How to use the xstate.assign function in xstate

To help you get started, we’ve selected a few xstate 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 coodoo / xstate-examples / crud-v1-services / src / fsm / actions.js View on Github external
console.log('[MODAL_DELETE_ITEM_RESULT]', e)
	const { result } = e
	ctx.notify(result.info)
})

export const modalErrorDataClose = assign((ctx, e) => {
	ctx.modalData = null
	ctx.notify('Loading Error dismissed')
})

export const modalErrorDataRetry = assign((ctx, e) => {
	ctx.modalData = null
	ctx.notify('Loading Error dismissed')
})

export const createNewItem = assign((ctx, e) => {
	// config which screen to exit to from creating new item screen
	ctx.exitNewItemTo = e.exitTo
})

// optimistic update, insert the item with local id
export const preSubmitNewItem = assign((ctx, e) => {
	const newItem = e.payload
	ctx.items.push(newItem)
	ctx.selectedItemId = newItem.id
})

// then invoke service to persist new item via external api call
export const submitNewItem = send(
	(ctx, e) => ({
		type: 'ServiceCreateItems',
		payload: e.payload,
github coodoo / xstate-examples / crud-v2-optimistic-update / src / fsm / actions.js View on Github external
import 'toasted-notes/src/styles.css'

// helper: toaster invocation as a side effect
const notify = msg => toaster.notify(msg, {
	position: 'bottom-right',
})

/* read item
-------------------------------------------------- */

export const reloadItems = send(
	{ type: 'SERVICE.LOAD.ITEMS' }, // the event to be sent
	{ to: 'ItemService' }, // the target servcie to receive that event
)

export const listDataSuccess = assign((ctx, evt) => {
	ctx.items = evt.data
})

export const listDataError = assign((ctx, e) => {
	ctx.modalData = {
		title: 'Fetching list data failed.',
		content: `Details: ${e.data}`,
		data: e.data,
	}
})

/* delete item
-------------------------------------------------- */

export const deleteItem = assign((ctx, e) => {
	const selectedItem = getItemById(ctx.items, ctx.selectedItemId)
github tolads / my-movie-lists / src / state / lists / listsMachine.js View on Github external
const getActiveItem = context =>
  context.items.find(item => item.id === context.active);

const listsMachine = Machine(
  {
    id: 'lists',
    initial: 'active',
    context: {
      active: id,
      items: [
        { id, label: 'Favourites', movies: ['tt0111161'] },
        { id: 2, label: 'Watchlist', movies: [] },
      ],
    },
    entry: assign({
      movies: () => spawn(moviesMachine),
    }),
    states: {
      inactive: {},
      active: {
        on: {
          '': {
            target: 'inactive',
            cond: 'noItems',
          },
          [RENAME_LIST]: {
            actions: 'renameList',
          },
          [DELETE_LIST]: {
            actions: 'deleteList',
          },
github wonderunit / storyboarder / src / js / xr / src / machines / uiMachine.js View on Github external
locked: (context, event) => true
    }),
    unlock: assign({
      locked: (context, event) => false
    }),
    hideUI: assign({
      isUIHidden: (context, event) => true
    }),
    showUI: assign({
      isUIHidden: (context, event) => false
    }),

    updateSelection: assign({
      selection: (context, event) => event.id
    }),
    clearSelection: assign({
      selection: (context, event) => null
    }),

    updateDraggingController: assign({
      draggingController: (context, event) => event.controller
    }),
    clearDraggingController: assign({
      draggingController: (context, event) => null
    })
  }
})

module.exports = machine
github kyleshevlin / room-sentiment / src / index.js View on Github external
on: {
          RESET: {
            target: 'idle',
            actions: ['resetLevel'],
          },
          RETRY: 'submitting',
        },
      },
    },
  },
  {
    actions: {
      resetLevel: assign({
        level: null,
      }),
      updateLevel: assign({
        level: (context, event) => event.level,
      }),
    },
    guards: {
      levelSelected: context => context.level !== null,
    },
    services: {
      submission: context =>
        client.mutate({
          mutation: createSentiment(context.level),
        }),
    },
  }
)

const Form = ({ current, send }) => {
github kyleshevlin / intro-to-state-machines-and-xstate-course / lessons / conditionally-transition-states-with-guards / before.js View on Github external
},
    states: {
      idle: {
        on: {
          SELECT_ITEM: 'vending',
          DEPOSIT_QUARTER: {
            actions: ['addQuarter'],
          },
        },
      },
      vending: {},
    },
  },
  {
    actions: {
      addQuarter: assign({
        deposited: context => context.deposited + 25,
      }),
    },
  }
)
github isaacplmann / sturdy-uis / src / machines / matching.ts View on Github external
}
    }
  },
  {
    actions: {
      setLeftSelectedItem: assign((ctx, event: any) => ({
        leftSelectedItem: event.selectedItem
          ? event.selectedItem
          : ctx.leftSelectedItem
      })),
      setRightSelectedItem: assign((ctx, event: any) => ({
        rightSelectedItem: event.selectedItem
          ? event.selectedItem
          : ctx.rightSelectedItem
      })),
      clearSelections: assign(() => ({
        leftSelectedItem: undefined,
        rightSelectedItem: undefined
      }))
    },
    guards: {
      areQuestionsAnswered: ctx => {
        return ctx.leftSelectedItem && ctx.rightSelectedItem;
      },
      isCorrect: () => true
    }
  }
);
github wonderunit / storyboarder / src / js / xr / src / machines / interactionMachine.js View on Github external
selection: (context, event) => event.intersection.id,
      selectionType: (context, event) => event.intersection.object.userData.type,
    }),
    clearSelection: assign({
      selection: (context, event) => null,
      selectionType: (context, event) => null
    }),

    updateDraggingController: assign({
      draggingController: (context, event) => event.controller.gamepad.index
    }),
    clearDraggingController: assign({
      draggingController: (context, event) => null
    }),

    updateTeleportDragController: assign({
      teleportDragController: (context, event) => event.controller.gamepad.index
    }),
    clearTeleportDragController: assign({
      teleportDragController: (context, event) => null
    }),
  },
  guards: {
    selectionPresent: (context, event) => context.selection != null,
    selectionNil: (context, event) => event.intersection == null,
    //setRediractedModeSelect : (context, event) => 

    eventHasSceneObjectIntersection: (context, event) => event.intersection != null && ['object', 'character', 'light', 'virtual-camera', 'image', 'attachable'].includes(event.intersection.type),
    eventHasBoneIntersection: (context, event) => event.intersection != null && event.intersection.bone,
    eventHasCharacterIntersection : (context, event) => context.selectionType === 'character',
    eventHasControlPointIntersection: (context, event) => event.intersection != null && event.intersection.controlPoint,
github DevanB / xstate-examples / trivia-game-react / src / machine.ts View on Github external
ANSWER_TRUE: {
            actions: 'updateAnswer',
          },
        },
      },
      results: {
        on: {
          PLAY_AGAIN: 'welcome',
        },
        exit: 'resetGame',
      },
    },
  },
  {
    actions: {
      resetGame: assign({
        currentQuestion: 0,
        currentQuestionDisplay: 1,
        questions: [],
        totalCorrectAnswers: 0,
      }),
      updateAnswer: assign((ctx, event: any) => ({
        questions: [
          ...ctx.questions.slice(0, ctx.currentQuestion),
          {
            ...ctx.questions[ctx.currentQuestion],
            userAnswer: event.answer,
            correct:
              ctx.questions[ctx.currentQuestion].correctAnswer === event.answer,
          },
          ...ctx.questions.slice(ctx.currentQuestion + 1),
        ],
github stefanoslig / angular-xstate / src / app / auth / +xstate / auth-machine.service.ts View on Github external
export class AuthMachine {
  authMachineOptions: Partial> = {
    services: {
      requestLogin: (_, event) =>
        this.authService
          .login({ email: event.username, password: event.password })
          .pipe(
            map(user => new LoginSuccess(user)),
            catchError(result => of(new LoginFail(result.error.errors)))
          )
    },
    guards: {
      isLoggedOut: () => !localStorage.getItem('jwtToken')
    },
    actions: {
      assignUser: assign((_, event) => ({
        user: event.userInfo
      })),
      assignErrors: assign((_, event) => ({
        errors: Object.keys(event.errors || {}).map(
          key => `${key} ${event.errors[key]}`
        )
      })),
      loginSuccess: (ctx, _) => {
        localStorage.setItem('jwtToken', ctx.user.token);
        this.router.navigateByUrl('');
      }
    }
  };

  private _authMachine = Machine(
    authMachineConfig