Skip to content

Instantly share code, notes, and snippets.

@ekafyi
Last active June 25, 2021 18:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekafyi/c9690f47c105cbb09e6704e0075cbe33 to your computer and use it in GitHub Desktop.
Save ekafyi/c9690f47c105cbb09e6704e0075cbe33 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const fetchLocations = async () => {
// fake response
return new Promise(resolve => setTimeout(() => resolve(["foo", "bar", "baz"]), 1000));
// return fetch(`/api/notion/locations`).then((response) => response.json());
}
const updateLocations = (_c, evt) => {
const { query } = evt;
console.log(query); // { AGES: "18_TO_49" }
// TODO build Fuse.js options from query, run, return
return ["foo"];
}
const updateActiveFilters = (ctx, evt) => {
return {
...ctx.activeFilters,
...evt.query
};
}
const filterValid = (_c, evt) => {
const { query } = evt;
// return typeof query == "object";
return (typeof query == "object") && query.hasOwnProperty("AGES" || "CITIES" || "REGISTRATIONS" || "TAGS");
};
const INITIAL_FILTERS = {
AGES: null,
CITIES: null,
REGISTRATIONS: null,
TAGS: null
}
const filterableState = {
type: "parallel",
states: {
data: {
type: "compound",
initial: "all",
on: {
APPLY_FILTER: {
target: "data.filtered",
cond: "filterValid",
actions: "handleFilter",
},
},
states: {
all: {},
filtered: {
on: {
RESET: {
target: "all",
actions: "handleReset",
},
}
},
},
},
// TODO next iteration
// multiFilters: {
// type: "compound",
// initial: "closed",
// on: {},
// states: {
// closed: {
// on: {
// OPEN_MULTI_FILTER: "open"
// }
// },
// open: {
// on: {
// APPLY: {
// target: ["closed", "#vax-machine.loaded.data.filtered"],
// },
// CANCEL: "closed"
// }
// },
// },
// },
},
};
const vaxMachine = Machine(
{
id: "vax-machine",
initial: "loading",
context: {
locations: [],
allLocations: [],
activeFilters: INITIAL_FILTERS,
},
states: {
loading: {
invoke: {
// id: "fetch-locations",
src: fetchLocations,
onDone: {
target: "loaded",
actions: assign({
locations: (context, event) => event.data,
allLocations: (context, event) => event.data
})
},
onError: {
target: "failure"
}
}
},
loaded: filterableState,
failure: {
on: {
RETRY: "loading"
}
}
},
},
{
actions: {
handleReset: assign({
locations: (context) => context.allLocations,
activeFilters: INITIAL_FILTERS,
}),
handleFilter: assign({
locations: updateLocations,
activeFilters: updateActiveFilters,
// fruit: '🍌', // pass this prop to the next (receiving) state
}),
},
guards: {
filterValid
},
services: {}
}
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment