()
| 57 | } |
| 58 | |
| 59 | export 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" |
nothing calls this directly
no test coverage detected