// Available variables: // - Machine // - interpret // - assign // - send // - sendParent // - spawn // - raise // - actions // - XState (all XState exports) const states = { IDLE: 'IDLE', FETCHING: 'FETCHING', }; const fetchNeeded = { target: states.FETCHING, cond: (ctx) => !ctx.loaded, }; const fetchedAlready = { target: states.IDLE, cond: (ctx) => ctx.loaded, actions: assign({ expanded: (ctx) => !ctx.expanded }), }; const machine = Machine( { id: 'result', initial: states.IDLE, context: { expanded: false, id: null, loaded: false, description: '', }, states: { [states.IDLE]: { on: { TOGGLE_EXPAND: [fetchNeeded, fetchedAlready], }, }, [states.FETCHING]: { invoke: { src: 'fetchResults', onDone: { target: states.IDLE, actions: assign({ expanded: true, loaded: true, description: (_, evt) => evt.data, }), }, }, }, }, }, { services: { fetchResults: (_ctx) => { console.log('Fetching suggestions!'); return new Promise((res, _rej) => { setTimeout( () => res('Visit ten places on our planet that are undergoing the biggest changes today.'), 1000, ); }); }, }, }, );