Skip to content

Instantly share code, notes, and snippets.

@valscion
Created November 7, 2019 15:28
Show Gist options
  • Save valscion/1fcbba63e5a34fbc45585b37d06b9964 to your computer and use it in GitHub Desktop.
Save valscion/1fcbba63e5a34fbc45585b37d06b9964 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const handleRequestSuccess = assign({
results: (_ctx, event) => {
if (event.type !== 'SEARCH_REQUEST_SUCCESS') {
throw new Error(
`Unexpected event type for handleRequestSuccess: "${event.type}"`
);
}
return event.results;
},
pagination: (_ctx, event) => {
if (event.type !== 'SEARCH_REQUEST_SUCCESS') {
throw new Error(
`Unexpected event type for handleRequestSuccess: "${event.type}"`
);
}
return event.pagination;
}
});
const handlePopState = assign({
searchCriteriaInitialValues: (_ctx, event) => {
if (event.type !== 'HISTORY_POPSTATE') {
throw new Error(
`Unexpected event type for handlePopState: "${event.type}"`
);
}
return event.searchCriteria;
},
searchCriteriaResetCount: ctx => ctx.searchCriteriaResetCount + 1,
results: (ctx, event) => {
if (event.type !== 'HISTORY_POPSTATE') {
return ctx.results;
}
return event.results;
},
pagination: (ctx, event) => {
if (event.type !== 'HISTORY_POPSTATE') {
return ctx.pagination;
}
return event.pagination;
}
});
const searchStateMachine = Machine({
id: 'search',
initial: 'idle',
context: {
// These initial values will be replaced when the component using this
// state machine is mounted, so the exact values used here do not matter.
pagination: null,
searchCriteriaInitialValues: null,
searchCriteriaResetCount: 0,
results: []
},
states: {
idle: {},
debouncing: {
on: {
TEXT_INPUT_BLUR: 'fetching'
},
after: [{ delay: 3000, target: 'fetching' }]
},
fetching: {
exit: ['clearPendingRequest'],
entry: ['startRequest'],
on: {
SEARCH_REQUEST_SUCCESS: {
target: 'idle',
actions: [handleRequestSuccess]
},
SEARCH_REQUEST_FAILURE: {
target: 'error',
actions: ['handleRequestFailure']
}
},
initial: 'fast',
states: {
fast: {
after: [{ delay: 5000, target: 'slow' }]
},
slow: {
type: 'final'
}
}
},
error: {
on: {
'': {
target: 'idle'
}
}
}
},
on: {
HISTORY_POPSTATE: {
target: 'idle',
actions: [handlePopState]
},
CHANGE_PAGE: 'fetching',
CHANGE_OPTION: 'fetching',
CHANGE_TEXT_INPUT: 'debouncing'
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment