Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Available variables:
- // - Machine
- // - interpret
- // - assign
- // - send
- // - sendParent
- // - spawn
- // - raise
- // - actions
- // - XState (all XState exports)
- const fetchMachine = Machine(
- {
- id: 'search',
- context: {
- searchFilters: {
- categoryIds: [],
- hierarchyPath: '',
- page: 1,
- sort: 'expectedValue',
- },
- isPriceSearch: true,
- results: {
- campsites: [],
- count: 0,
- facets: {},
- },
- },
- initial: 'idle',
- states: {
- idle: {
- on: {
- SEARCH: 'search',
- },
- },
- search: {
- initial: 'checking',
- onEntry: ['setFilters', 'startTimer'],
- on: {
- SEARCH: 'search',
- },
- states: {
- checking: {
- on: {
- '': [
- { target: 'price', cond: 'isPriceSearch' },
- { target: 'nonPrice' },
- ],
- },
- },
- price: {
- meta: {
- sortOptions: [
- 'expectedValue',
- 'ratingSort',
- 'priceSort',
- 'bestSellerSort',
- ],
- },
- initial: 'searching',
- states: {
- searching: {
- onExit: 'stopTimer',
- invoke: [
- {
- src: 'doPriceSearch',
- onDone: {
- target: '#results',
- actions: 'setResults',
- },
- onError: '#search.error',
- },
- {
- src: 'fetchFacetsCount',
- },
- ],
- },
- },
- },
- nonPrice: {
- meta: {
- sortOptions: ['expectedValue', 'ratingSort', 'bestSellerSort'],
- },
- initial: 'searching',
- states: {
- searching: {
- onExit: 'stopTimer',
- invoke: [
- {
- src: 'doNonPriceSearch',
- onDone: {
- target: '#results',
- actions: 'setResults',
- },
- onError: '#search.error',
- },
- {
- src: 'fetchFacetsCount',
- },
- ],
- },
- },
- },
- },
- },
- results: {
- id: "results"
- },
- error: {
- onEntry: ['setError'],
- on: {
- SEARCH: 'search',
- },
- onExit: ['clearError'],
- },
- },
- },
- {
- actions: {
- clearError: assign(_ => {
- return { errorMessage: undefined }
- }),
- setError: assign((_, { data }) => {
- return { errorMessage: "data.toString()" }
- }),
- setFilters: assign((_, { searchFilters }) => {
- let isPrice = false
- const filters = { ...searchFilters }
- if (searchFilters) {
- isPrice = getIsPriceSearch(searchFilters)
- if (isPrice) {
- filters.party = getParty(filters.party)
- }
- }
- return { searchFilters: filters, isPriceSearch: isPrice }
- }),
- setResults: assign((_, { data }) => {
- return { results: data }
- }),
- startTimer: assign(_ => {
- return { startTime: performance.now() / 1000 }
- }),
- stopTimer: assign(_ => {
- return { endTime: performance.now() / 1000 }
- }),
- },
- guards: {
- isPriceSearch: ({ isPriceSearch }) => {
- return true
- },
- },
- }
- );
- const getIsPriceSearch = (searchFilters) => {
- const range = searchFilters.range
- return Boolean(range && range.arrive && range.depart)
- }
- const getParty = (party) => {
- return typeof party !== 'undefined'
- ? party
- : {
- adults: 2,
- childAges: [],
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement