Skip to content

Commit

Permalink
Update to use @tanstack/react-query
Browse files Browse the repository at this point in the history
  • Loading branch information
lucemans committed Nov 26, 2024
1 parent 7e488e2 commit 76872df
Show file tree
Hide file tree
Showing 15 changed files with 336 additions and 151 deletions.
2 changes: 1 addition & 1 deletion web/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"v3xlabs"
],
"env": {
"node": true
"browser": true
},
"rules": {}
}
4 changes: 3 additions & 1 deletion web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
"@radix-ui/react-avatar": "^1.1.1",
"@radix-ui/react-dropdown-menu": "^2.1.2",
"@radix-ui/react-hover-card": "^1.1.2",
"@radix-ui/react-label": "^2.1.0",
"@tanstack/react-query": "^5.x.x",
"@tanstack/react-router": "^1.45.14",
"@vitejs/plugin-react": "^4.3.1",
"autoprefixer": "^10.4.19",
Expand All @@ -29,8 +31,8 @@
"postcss": "^8.4.38",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-icons": "^5.3.0",
"react-leaflet": "^4.2.1",
"swr": "^2.2.5",
"tailwindcss": "^3.4.3",
"ts-pattern": "^5.5.0",
"ua-parser-js": "^1.0.38",
Expand Down
74 changes: 55 additions & 19 deletions web/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

59 changes: 31 additions & 28 deletions web/src/api/core.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,37 @@
import useSWR from 'swr';
import { useMutation, useQuery } from '@tanstack/react-query';

import { useAuth } from './auth';
export const BASE_URL = 'http://localhost:3000';

const BASE_URL = 'http://localhost:3000';
// Replace SWR fetcher with axios or fetch implementation
// eslint-disable-next-line no-undef
export async function fetcher<T>(url: string, init?: RequestInit): Promise<T> {
const response = await fetch(url, init);

export const useHttp = <K>(url: string) => {
const { token, clearAuthToken } = useAuth();
if (!response.ok) {
throw new Error('Network response was not ok');
}

return useSWR(token && url, async (): Promise<K | null> => {
const headers = new Headers();
return response.json();
}

headers.append('Authorization', 'Bearer ' + token);

try {
const response = await fetch(BASE_URL + url, { headers });

if (response.status === 401) {
console.log('Token expired, clearing token');
clearAuthToken();

return null;
}

const data = (await response.json()) as K;

return data as K;
} catch (error) {
console.error(error);

return null;
}
// Replace useSWR hooks with useQuery
export function useHttp<T>(key: string) {
return useQuery({
queryKey: [key],
queryFn: () => fetcher<T>(key),
});
}

// For mutations (if you have any POST/PUT/DELETE operations)
export function useUpdateData<T>(url: string) {
return useMutation({
mutationFn: (data: T) =>
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
}).then((response) => response.json()),
});
};
}
44 changes: 17 additions & 27 deletions web/src/api/geoip.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,20 @@
import useSWR from 'swr';
import { useQuery } from '@tanstack/react-query';

type GeoIpResponse = {
ip_address: string;
latitude: number;
longitude: number;
postal_code: string;
continent_code: string;
continent_name: string;
country_code: string;
country_name: string;
region_code: string;
region_name: string;
province_code: string;
province_name: string;
city_name: string;
timezone: string;
};
import { BASE_URL, fetcher } from './core';

export const useGeoIp = (ip: string) =>
useSWR(
'geo:' + ip,
async () => {
const response = await fetch('https://api.geoip.rs/?ip=' + ip);
const data = await response.json();
interface GeoIPResponse {
ip: string;
country: string;
city?: string;
// Add other fields based on your API response
}

return data as GeoIpResponse;
},
{ errorRetryInterval: 10_000 }
);
export function useGeoIp() {
return useQuery({
queryKey: ['geoip'],
queryFn: () => fetcher<GeoIPResponse>(`${BASE_URL}/api/geoip`),
// Add any specific options you need:
// staleTime: 5 * 60 * 1000, // Consider data fresh for 5 minutes
// cacheTime: 30 * 60 * 1000, // Keep data in cache for 30 minutes
});
}
52 changes: 23 additions & 29 deletions web/src/api/me.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,26 @@
import { useHttp } from './core';
import { useQuery } from '@tanstack/react-query';

export type ApiMeResponse = {
id: number;
oauth_sub: string;
import { useAuth } from './auth';
import { BASE_URL, fetcher } from './core';

interface MeResponse {
id: string;
name: string;
picture: string;
// oauth_data: {
// sub: string;
// name: string;
// given_name: string;
// family_name: string;
// middle_name: null;
// nickname: null;
// preferred_username: null;
// profile: null;
// picture: string;
// website: null;
// email: string;
// email_verified: boolean;
// gender: null;
// birthdate: null;
// zoneinfo: null;
// locale: null;
// phone_number: null;
// phone_number_verified: boolean;
// address: null;
// updated_at: null;
// };
};
picture?: string;
// Add other fields as needed
}

export function useApiMe() {
const { token } = useAuth();

export const useApiMe = () => useHttp<ApiMeResponse>('/api/me');
return useQuery({
queryKey: ['me', token],
queryFn: () =>
fetcher<MeResponse>(`${BASE_URL}/api/me`, {
headers: {
Authorization: `Bearer ${token}`,
},
}),
enabled: !!token, // Only run query if token exists
});
}
3 changes: 2 additions & 1 deletion web/src/components/Navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ export const Navbar = () => {
<div className="h-full flex items-center">
{[
['/', 'Home'],
['/create', 'Create'],
['/sessions', 'Sessions'],
].map(([path, name]) => (
<Link
Expand All @@ -39,7 +40,7 @@ export const Navbar = () => {
))}
</div>
</div>
{meData && (
{token && meData && (
<div className="h-full border-l">
<DropdownMenu.Root>
<DropdownMenu.Trigger asChild>
Expand Down
Loading

0 comments on commit 76872df

Please sign in to comment.