MCPcopy Create free account
hub / github.com/electric-sql/electric / Example

Function Example

examples/tanstack/src/Example.tsx:59–128  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

57}
58
59export const Example = () => {
60 const queryClient = useQueryClient()
61 const { data: items } = useShape<Item>(itemShape())
62 const submissions: Item[] = useMutationState({
63 filters: { status: `pending` },
64 select: (mutation) => mutation.state.context as Item,
65 }).filter((item) => item !== undefined)
66
67 const { mutateAsync: addItemMut } = useMutation({
68 scope: { id: `items` },
69 mutationKey: [`add-item`],
70 mutationFn: (newId: string) => createItem(newId),
71 onMutate: (id) => {
72 const optimisticItem: Item = { id }
73 return optimisticItem
74 },
75 })
76
77 const { mutateAsync: clearItemsMut, isPending: isClearing } = useMutation({
78 scope: { id: `items` },
79 mutationKey: [`clear-items`],
80 mutationFn: (numItems: number) => clearItems(numItems),
81 onMutate: () => {
82 const addMutations = queryClient
83 .getMutationCache()
84 .findAll({ mutationKey: [`add-item`] })!
85 addMutations?.forEach((mut) => queryClient.getMutationCache().remove(mut))
86 },
87 })
88
89 // Merge data from shape & optimistic data from fetchers. This removes
90 // possible duplicates as there's a potential race condition where
91 // useShape updates from the stream slightly before the action has finished.
92 const itemsMap = new Map<string, Item>()
93 if (!isClearing) {
94 items.concat(submissions).forEach((item) => {
95 itemsMap.set(item.id, { ...itemsMap.get(item.id), ...item })
96 })
97 } else {
98 submissions.forEach((item) => itemsMap.set(item.id, item))
99 }
100
101 return (
102 <div>
103 <div>
104 <button
105 type="submit"
106 className="button"
107 onClick={() => addItemMut(uuidv4())}
108 value="add"
109 >
110 Add
111 </button>
112 <button
113 type="submit"
114 className="button"
115 onClick={() => clearItemsMut(items.length)}
116 value="clear"

Callers

nothing calls this directly

Calls 12

useShapeFunction · 0.90
itemShapeFunction · 0.85
clearItemsFunction · 0.85
filterMethod · 0.80
concatMethod · 0.80
createItemFunction · 0.70
removeMethod · 0.65
setMethod · 0.65
getMethod · 0.65
forEachMethod · 0.45
mapMethod · 0.45
valuesMethod · 0.45

Tested by

no test coverage detected