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

Users.tsx

84 lines1.9 KB

1import { queryOptions, useSuspenseQuery } from '@tanstack/react-query'
2​
3export interface Geo {
4 lat: string
5 lng: string
6}
7​
8export interface Address {
9 street: string
10 suite: string
11 city: string
12 zipcode: string
13 geo: Geo
15​
16export interface Company {
17 name: string
18 catchPhrase: string
19 bs: string
21​
22export interface User {
23 id: number
24 name: string
25 username: string
26 email: string
27 address: Address
28 phone: string
29 website: string
30 company: Company
32​
33export const getUsers = async (): Promise<Array<User>> => {
34 const response = await fetch('https://jsonplaceholder.typicode.com/users')
35 const users: Array<User> = await response.json()
36 return users
38​
39export const searchUsers = async (search: string): Promise<Array<User>> => {
40 const users = await getUsers()
41 const normalizedSearch = search.toLowerCase()
42 return users.filter(
43 (user) =>
44 user.name.toLowerCase().includes(normalizedSearch) ||
45 user.username.toLowerCase().includes(normalizedSearch),
46 )
48​
49export const usersQueryOptions = (search: string) =>
50 queryOptions({
51 queryKey: ['users', search],
52 queryFn: async () => {
53 return await searchUsers(search)
54 },
55 })
56​
57export interface UsersProps {
58 search: string
60​
61export const Users = ({ search }: UsersProps) => {
62 const { data: users } = useSuspenseQuery(usersQueryOptions(search))
63​
64 return (
65 <table className="table-auto">
66 <thead>
67 <tr className="border text-left">
68 <th className="p-4">Username</th>
69 <th className="p-4">Name</th>
70 <th className="p-4">Email</th>
71 </tr>
72 </thead>
73 <tbody>
74 {users.map((user) => (
75 <tr key={user.id} className="border">
76 <td className="p-4">{user.username}</td>
77 <td className="p-4">{user.name}</td>
78 <td className="p-4">{user.email}</td>
79 </tr>
80 ))}
81 </tbody>
82 </table>
83 )