reduce
reduce takes a reducer function for changing the context of the machine. A common use case is to set values coming from form fields.
The reducer receives the current context and the event, and the value it returns becomes the new context. Always return the context, even if unchanged. For side effects that don’t change context, use action.
When a transition has several reducers and actions, they run in the order they are listed, and each receives the context returned by the reducers before it.
Reducers can also be passed directly to state, where they run whenever the machine enters that state.
In this example are implementing a login form that sets the login and password properties on the context.
import { createMachine, reduce, state, transition } from 'robot3';
const machine = createMachine({
idle: state(
transition('login', 'idle',
reduce((ctx, ev) => ({ ...ctx, login: ev.target.value }))
),
transition('password', 'idle',
reduce((ctx, ev) => ({ ...ctx, password: ev.target.value }))
),
transition('submit', 'complete')
),
complete: state()
});