Skip to content
Source
Sign inSign up
TanStack/router
Open History to see the last commit

users.tsx

38 lines975 Bytes

1import { queryOptions } from '@tanstack/react-query'
2import { createIsomorphicFn } from '@tanstack/react-start'
3import { getRequestUrl } from '@tanstack/react-start/server'
4import axios from 'redaxios'
5​
6export type User = {
7 id: number
8 name: string
9 email: string
11​
12const getOrigin = createIsomorphicFn()
13 .server(() => getRequestUrl().origin)
14 .client(() => window.location.origin)
15​
16export const usersQueryOptions = () =>
17 queryOptions({
18 queryKey: ['users'],
19 queryFn: () =>
20 axios
21 .get<Array<User>>(getOrigin() + '/api/users')
22 .then((r) => r.data)
23 .catch(() => {
24 throw new Error('Failed to fetch users')
25 }),
26 })
27​
28export const userQueryOptions = (id: string) =>
29 queryOptions({
30 queryKey: ['users', id],
31 queryFn: () =>
32 axios
33 .get<User>(getOrigin() + '/api/users/' + id)
34 .then((r) => r.data)
35 .catch(() => {
36 throw new Error('Failed to fetch user')
37 }),
38 })