Skip to content

Commit

Permalink
Merge pull request #5 from hackclub/cjdenio/ky
Browse files Browse the repository at this point in the history
switch to ky
  • Loading branch information
cjdenio authored Jun 7, 2024
2 parents 36808a7 + c219cf9 commit 24ac751
Show file tree
Hide file tree
Showing 21 changed files with 104 additions and 116 deletions.
34 changes: 16 additions & 18 deletions App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { SWRConfig } from "swr";

import AuthContext from "./src/auth";
import { getStateFromPath } from "./src/getStateFromPath";
import useClient from "./src/lib/client";
import { TabParamList } from "./src/lib/NavigatorParamList";
import Navigator from "./src/Navigator";
import Login from "./src/pages/login";
Expand Down Expand Up @@ -49,29 +50,26 @@ const linking: LinkingOptions<TabParamList> = {
export default function App() {
const [isLoading, setIsLoading] = useState(true);
const [token, setToken] = useState<string | null>(null);
const hcb = useClient(token);

const scheme = useColorScheme();

const fetcher = useCallback(
(url: string) =>
fetch(process.env.EXPO_PUBLIC_API_BASE + url, {
headers: { Authorization: `Bearer ${token}` },
}).then(async (res) => {
const body = await res.json();

if (!res.ok) {
if (body.error === "invalid_auth") {
// OAuth token either expired or was revoked
setToken("");
return;
} else {
throw body;
}
async (url: string) => {
try {
return await hcb(url).json();
} catch (error) {
if (
error.name === "HTTPError" &&
(await error.response.json()).error === "invalid_auth"
) {
setToken("");
} else {
throw error;
}

return body;
}),
[token],
}
},
[hcb],
);

useEffect(() => {
Expand Down
12 changes: 12 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
"expo-system-ui": "~2.9.3",
"expo-web-browser": "~12.8.2",
"humanize-string": "^3.0.0",
"ky": "^1.2.3",
"lodash": "^4.17.21",
"react": "18.2.0",
"react-native": "0.73.4",
Expand Down
8 changes: 4 additions & 4 deletions src/Navigator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,9 @@ const Tab = createBottomTabNavigator<TabParamList>();

export default function Navigator() {
const { data: missingReceiptData } = useSWR<PaginatedResponse<never>>(
`/user/transactions/missing_receipt`,
`user/transactions/missing_receipt`,
);
const { data: invitations } = useSWR<Invitation[]>(`/user/invitations`);
const { data: invitations } = useSWR<Invitation[]>(`user/invitations`);

const scheme = useColorScheme();
const { colors: themeColors } = useTheme();
Expand Down Expand Up @@ -112,8 +112,8 @@ export default function Navigator() {
dismissButtonStyle: "cancel",
},
).then(() => {
mutate("/user/organizations");
mutate("/user/invitations");
mutate("user/organizations");
mutate("user/invitations");
})
}
/>
Expand Down
2 changes: 1 addition & 1 deletion src/components/AdminTools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export const AdminToolsStyle: ViewStyle = {
export default function AdminTools(
props: PropsWithChildren<{ style?: ViewStyle; onPress?: () => void }>,
) {
const { data: user } = useSWR<User>("/user");
const { data: user } = useSWR<User>("user");

if (!user?.admin) return null;

Expand Down
2 changes: 1 addition & 1 deletion src/components/transaction/ReceiptList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default function ReceiptList({
}) {
const { params } = useRoute<RouteProp<StackParamList, "Transaction">>();
const { data: receipts, isLoading } = useSWR<Receipt[]>(
`/organizations/${params.orgId}/transactions/${transaction.id}/receipts`,
`organizations/${params.orgId}/transactions/${transaction.id}/receipts`,
);

const { colors: themeColors } = useTheme();
Expand Down
4 changes: 1 addition & 3 deletions src/components/transaction/types/BankFeeTransaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ export default function BankFeeTransaction({
orgId,
navigation,
}: TransactionViewProps) {
const { data: organization } = useSWR<Organization>(
`/organizations/${orgId}`,
);
const { data: organization } = useSWR<Organization>(`organizations/${orgId}`);

return (
<View>
Expand Down
4 changes: 2 additions & 2 deletions src/components/transaction/types/TransferTransaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ export default function TransferTransaction({
navigation,
...props
}: TransactionViewProps<TransactionTransfer>) {
const { data: userOrgs } = useSWR<Organization[]>(`/user/organizations`);
const { data: user } = useSWR<User>("/user");
const { data: userOrgs } = useSWR<Organization[]>(`user/organizations`);
const { data: user } = useSWR<User>("user");

const userInFromOrg =
user?.admin || userOrgs?.some((org) => org.id == transfer.from.id);
Expand Down
19 changes: 19 additions & 0 deletions src/lib/client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import ky from "ky";
import { useContext, useMemo } from "react";

import AuthContext from "../auth";

export default function useClient(token?: string | null | undefined) {
const { token: _token } = useContext(AuthContext);

return useMemo(
() =>
ky.create({
prefixUrl: process.env.EXPO_PUBLIC_API_BASE,
headers: {
Authorization: `Bearer ${token || _token}`,
},
}),
[token, _token],
);
}
4 changes: 2 additions & 2 deletions src/lib/organization/useTransactions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ export function getKey(orgId: string) {
if (previousPageData?.has_more === false) return null;

if (index === 0)
return `/organizations/${orgId}/transactions?limit=${PAGE_SIZE}`;
return `organizations/${orgId}/transactions?limit=${PAGE_SIZE}`;

return `/organizations/${orgId}/transactions?limit=${PAGE_SIZE}&after=${
return `organizations/${orgId}/transactions?limit=${PAGE_SIZE}&after=${
previousPageData!.data[previousPageData!.data.length - 1].id
}`;
};
Expand Down
38 changes: 9 additions & 29 deletions src/pages/Invitation.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Ionicons } from "@expo/vector-icons";
import { useTheme } from "@react-navigation/native";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { useContext, useEffect } from "react";
import { useEffect } from "react";
import {
View,
Text,
Expand All @@ -13,8 +13,8 @@ import {
import useSWR, { useSWRConfig } from "swr";
import useSWRMutation from "swr/mutation";

import AuthContext from "../auth";
import Button from "../components/Button";
import useClient from "../lib/client";
import { StackParamList } from "../lib/NavigatorParamList";
import Invitation from "../lib/types/Invitation";
import palette from "../palette";
Expand All @@ -28,10 +28,10 @@ export default function InvitationPage({
params: { inviteId, invitation: _invitation },
},
}: Props) {
const { token } = useContext(AuthContext);
const hcb = useClient();

const { data: invitation } = useSWR<Invitation>(
`/user/invitations/${inviteId}`,
`user/invitations/${inviteId}`,
{ fallbackData: _invitation },
);

Expand All @@ -56,18 +56,8 @@ export default function InvitationPage({
never,
Invitation[]
>(
`/user/invitations`,
() =>
fetch(
process.env.EXPO_PUBLIC_API_BASE +
`/user/invitations/${inviteId}/accept`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
},
),
`user/invitations`,
() => hcb.post(`user/invitations/${inviteId}/accept`).json(),
{
populateCache: (_, invitations) =>
invitations?.filter((i) => i.id != inviteId) || [],
Expand All @@ -77,7 +67,7 @@ export default function InvitationPage({
orgId: invitation!.organization.id,
organization: invitation!.organization,
});
mutate(`/user/organizations`);
mutate(`user/organizations`);
},
},
);
Expand All @@ -89,18 +79,8 @@ export default function InvitationPage({
never,
Invitation[]
>(
`/user/invitations`,
() =>
fetch(
process.env.EXPO_PUBLIC_API_BASE +
`/user/invitations/${inviteId}/reject`,
{
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
},
},
),
`user/invitations`,
() => hcb.post(`user/invitations/${inviteId}/reject`).json(),
{
populateCache: (_, invitations) =>
invitations?.filter((i) => i.id != inviteId) || [],
Expand Down
4 changes: 2 additions & 2 deletions src/pages/Receipts.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ function Transaction({
try {
await fetch(
process.env.EXPO_PUBLIC_API_BASE +
`/organizations/${transaction.organization.id}/transactions/${transaction.id}/receipts`,
`organizations/${transaction.organization.id}/transactions/${transaction.id}/receipts`,
{
method: "POST",
headers: {
Expand Down Expand Up @@ -143,7 +143,7 @@ type Props = NativeStackScreenProps<
export default function ReceiptsPage({ navigation: _navigation }: Props) {
const { data, mutate, isLoading } = useSWR<{
data: (TransactionCardCharge & { organization: Organization })[];
}>("/user/transactions/missing_receipt");
}>("user/transactions/missing_receipt");

useFocusEffect(() => {
mutate();
Expand Down
29 changes: 10 additions & 19 deletions src/pages/RenameTransaction.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useTheme } from "@react-navigation/native";
import { NativeStackScreenProps } from "@react-navigation/native-stack";
import { useContext, useState } from "react";
import { useState } from "react";
import {
ActivityIndicator,
StatusBar,
Expand All @@ -12,7 +12,7 @@ import useSWR, { useSWRConfig } from "swr";
import { unstable_serialize } from "swr/infinite";
import useSWRMutation from "swr/mutation";

import AuthContext from "../auth";
import useClient from "../lib/client";
import { StackParamList } from "../lib/NavigatorParamList";
import { getKey } from "../lib/organization/useTransactions";
import Transaction from "../lib/types/Transaction";
Expand All @@ -26,16 +26,16 @@ export default function RenameTransactionPage({
},
navigation,
}: Props) {
const { token } = useContext(AuthContext);
const { colors: themeColors } = useTheme();
const { mutate } = useSWRConfig();
const hcb = useClient();

const {
data: memoSuggestions,
isLoading,
isValidating,
} = useSWR<string[]>(
`/organizations/${orgId}/transactions/${transaction.id}/memo_suggestions`,
`organizations/${orgId}/transactions/${transaction.id}/memo_suggestions`,
{ revalidateOnMount: true },
);

Expand All @@ -44,22 +44,13 @@ export default function RenameTransactionPage({
);

const { trigger } = useSWRMutation(
`/organizations/${orgId}/transactions/${transaction.id}`,
`organizations/${orgId}/transactions/${transaction.id}`,
() =>
fetch(
process.env.EXPO_PUBLIC_API_BASE +
`/organizations/${orgId}/transactions/${transaction.id}`,
{
method: "PATCH",
body: JSON.stringify({
memo,
}),
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
},
},
).then((res) => res.json()),
hcb
.patch(`organizations/${orgId}/transactions/${transaction.id}`, {
json: { memo },
})
.json(),
{
optimisticData(currentData: Transaction) {
return { ...currentData, memo };
Expand Down
2 changes: 1 addition & 1 deletion src/pages/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ export default function SettingsPage(
});
}, []);

const { data: user } = useSWR<User>("/user");
const { data: user } = useSWR<User>("user");

const handleClick = (iconName: string) => {
AppIcon.setAppIcon(iconName.toString());
Expand Down
6 changes: 3 additions & 3 deletions src/pages/Transaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ export default function TransactionPage({
Transaction & { organization?: Organization }
>(
orgId
? `/organizations/${orgId}/transactions/${transactionId}`
: `/transactions/${transactionId}`,
? `organizations/${orgId}/transactions/${transactionId}`
: `transactions/${transactionId}`,
{ fallbackData: _transaction },
);
const { data: comments } = useSWR<IComment[]>(
() =>
`/organizations/${
`organizations/${
orgId || transaction!.organization!.id
}/transactions/${transactionId}/comments`,
);
Expand Down
Loading

0 comments on commit 24ac751

Please sign in to comment.