Skip to content

Commit 0d26669

Browse files
docs(react): mock db for robust tanstack query integration
Co-authored-by: Harry Whorlow <[email protected]>
1 parent bb977cd commit 0d26669

File tree

1 file changed

+30
-5
lines changed
  • examples/react/query-integration/src

1 file changed

+30
-5
lines changed

examples/react/query-integration/src/index.tsx

+30-5
Original file line numberDiff line numberDiff line change
@@ -20,20 +20,39 @@ function FieldInfo({ field }: { field: AnyFieldApi }) {
2020
)
2121
}
2222

23+
class DB {
24+
private data: { firstName: string; lastName: string }
25+
26+
constructor() {
27+
this.data = { firstName: 'FirstName', lastName: 'LastName' }
28+
}
29+
30+
getData(): { firstName: string; lastName: string } {
31+
return { ...this.data }
32+
}
33+
34+
async saveUser(value: { firstName: string; lastName: string }) {
35+
this.data = value
36+
return value
37+
}
38+
}
39+
40+
// Dummy Database to emulate server-side actions
41+
const db = new DB()
42+
2343
export default function App() {
24-
const { data, isLoading } = useQuery({
44+
const { data, isLoading, refetch } = useQuery({
2545
queryKey: ['data'],
2646
queryFn: async () => {
2747
await new Promise((resolve) => setTimeout(resolve, 1000))
28-
return { firstName: 'FirstName', lastName: 'LastName' }
48+
return db.getData()
2949
},
3050
})
3151

3252
const saveUserMutation = useMutation({
3353
mutationFn: async (value: { firstName: string; lastName: string }) => {
3454
await new Promise((resolve) => setTimeout(resolve, 1000))
35-
console.log(value)
36-
return value
55+
db.saveUser(value)
3756
},
3857
})
3958

@@ -42,9 +61,15 @@ export default function App() {
4261
firstName: data?.firstName ?? '',
4362
lastName: data?.lastName ?? '',
4463
},
45-
onSubmit: async ({ value }) => {
64+
onSubmit: async ({ formApi, value }) => {
4665
// Do something with form data
4766
await saveUserMutation.mutateAsync(value)
67+
68+
// Invalidating query to recheck fresh data
69+
await refetch()
70+
71+
// Reset the form to start-over with a clean state
72+
formApi.reset()
4873
},
4974
})
5075

0 commit comments

Comments
 (0)