@@ -14,7 +14,7 @@ import { ConfiguredNodeTypeMap } from './staticObjects'
14
14
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
15
15
import { NodeSetQueryOptions } from './queryOptions'
16
16
import { createNode } from './functionModule'
17
-
17
+ import { v4 as uuid } from 'uuid'
18
18
19
19
export const useNodeSet = <
20
20
ParentNodeType extends NodeSetParentTypes<ConfiguredNodeTypeMap>,
@@ -33,17 +33,47 @@ export const useNodeSet = <
33
33
const queryClient = useQueryClient()
34
34
const { data, error } = useQuery(queryOptions)
35
35
const createNodeMutation = useMutation({
36
- mutationFn: async (initialState: NodeState<ConfiguredNodeTypeMap[ChildNodeType]>) => {
36
+ mutationFn: async ({
37
+ nodeId,
38
+ createdAt,
39
+ updatedAt,
40
+ nodeType,
41
+ ...initialState
42
+ }: NodeShape<ConfiguredNodeTypeMap[ChildNodeType]>) => {
37
43
return await createNode({
38
44
parentNodeKeys: [parentNodeKey],
39
45
childNodeType,
40
- initialState
46
+ initialState: initialState as NodeState<ConfiguredNodeTypeMap[ChildNodeType]>,
47
+ providedNodeId: nodeId,
48
+ })
49
+ },
50
+ onMutate: async (newNode) => {
51
+ await queryClient.cancelQueries({queryKey: queryOptions.queryKey})
52
+ const previousData = queryClient.getQueryData(queryOptions.queryKey)
53
+ queryClient.setQueryData(queryOptions.queryKey, oldData => {
54
+ if (!oldData) return [newNode]
55
+ return [...oldData, newNode]
41
56
})
57
+ return { previousData }
58
+ },
59
+ onError: (err, newData, context) => {
60
+ queryClient.setQueryData(queryOptions.queryKey, context?.previousData)
42
61
},
43
62
onSuccess: () => queryClient.invalidateQueries({
44
63
queryKey: [parentNodeKey.nodeType, parentNodeKey.nodeId, childNodeType]
45
64
})
46
65
})
47
- return { data, error, createNodeMutation }
66
+ return {
67
+ data, error, createNode: (...[initialState, handlers]: [
68
+ NodeState<ConfiguredNodeTypeMap[ChildNodeType]>,
69
+ Parameters<typeof createNodeMutation['mutate']>[1]?
70
+ ]) => createNodeMutation.mutateAsync({
71
+ nodeId: uuid(),
72
+ createdAt: new Date().getTime(),
73
+ updatedAt: new Date().getTime(),
74
+ nodeType: childNodeType,
75
+ ...initialState
76
+ }, handlers)
77
+ }
48
78
}
49
79
`
0 commit comments