Skip to content

Commit

Permalink
chore: use trpc queryOptions in example (#1153)
Browse files Browse the repository at this point in the history
  • Loading branch information
juliusmarminge authored Feb 18, 2025
1 parent b2f3f87 commit 02a800c
Show file tree
Hide file tree
Showing 7 changed files with 146 additions and 137 deletions.
7 changes: 4 additions & 3 deletions examples/minimal-expo/app/_layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import "./styles.css";

import FeatherIcon from "@expo/vector-icons/Feather";
import { BottomSheetModal, BottomSheetView } from "@gorhom/bottom-sheet";
import { QueryClientProvider } from "@tanstack/react-query";
import { Image } from "expo-image";
import { Stack } from "expo-router";
import { StatusBar } from "expo-status-bar";
Expand All @@ -11,11 +12,11 @@ import {
RectButton,
} from "react-native-gesture-handler";

import { TRPCProvider } from "~/lib/trpc";
import { queryClient } from "~/lib/trpc";

export default function RootLayout() {
return (
<TRPCProvider>
<QueryClientProvider client={queryClient}>
<GestureHandlerRootView style={{ flex: 1 }}>
<Stack
screenOptions={{
Expand All @@ -31,7 +32,7 @@ export default function RootLayout() {
</GestureHandlerRootView>

<StatusBar />
</TRPCProvider>
</QueryClientProvider>
);
}

Expand Down
9 changes: 6 additions & 3 deletions examples/minimal-expo/app/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useState } from "react";
import { FlashList } from "@shopify/flash-list";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { Stack } from "expo-router";
import { ActivityIndicator, RefreshControl, Text, View } from "react-native";

Expand All @@ -8,8 +9,8 @@ import { UploadActionDrawer } from "~/components/upload-drawer";
import { trpc } from "~/lib/trpc";

export default function HomeScreen() {
const utils = trpc.useUtils();
const { data: files, isPending } = trpc.getFiles.useQuery();
const queryClient = useQueryClient();
const { data: files, isPending } = useQuery(trpc.getFiles.queryOptions());

const [refreshing, setRefreshing] = useState(false);
const [isScrolling, setIsScrolling] = useState(false);
Expand All @@ -34,7 +35,9 @@ export default function HomeScreen() {
refreshing={refreshing}
onRefresh={async () => {
setRefreshing(true);
await utils.getFiles.invalidate();
await queryClient.invalidateQueries(
trpc.getFiles.queryFilter(),
);
setRefreshing(false);
}}
tintColor={"#ccc"}
Expand Down
25 changes: 15 additions & 10 deletions examples/minimal-expo/components/file-item.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useRef } from "react";
import FeatherIcon from "@expo/vector-icons/Feather";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import * as Haptics from "expo-haptics";
import { Link } from "expo-router";
import { Animated, Text, View } from "react-native";
Expand All @@ -17,16 +18,20 @@ export function FileItem({
}: {
item: RouterOutputs["getFiles"][number];
}) {
const utils = trpc.useUtils();
const { mutate: deleteFile } = trpc.deleteFile.useMutation({
onMutate: () => {
// Optimicially remove the file from the list
const files = utils.getFiles.getData() ?? [];
const newFiles = files.filter((f) => f.key !== item.key);
utils.getFiles.setData(undefined, newFiles);
},
onSettled: () => utils.getFiles.invalidate(),
});
const queryClient = useQueryClient();
const { mutate: deleteFile } = useMutation(
trpc.deleteFile.mutationOptions({
onMutate: () => {
// Optimicially remove the file from the list
const files = queryClient.getQueryData(trpc.getFiles.queryKey()) ?? [];
const newFiles = files.filter((f) => f.key !== item.key);
queryClient.setQueryData(trpc.getFiles.queryKey(), newFiles);
},
onSettled: async () => {
await queryClient.invalidateQueries(trpc.getFiles.queryFilter());
},
}),
);

const threshhold = 64;
const height = useRef(new Animated.Value(threshhold)).current;
Expand Down
7 changes: 4 additions & 3 deletions examples/minimal-expo/components/upload-drawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
BottomSheetModalProvider,
BottomSheetView,
} from "@gorhom/bottom-sheet";
import { useQueryClient } from "@tanstack/react-query";
import { openSettings } from "expo-linking";
import { useRouter } from "expo-router";
import { ActivityIndicator, Alert, Pressable, Text, View } from "react-native";
Expand All @@ -15,7 +16,7 @@ import { useDocumentUploader, useImageUploader } from "~/lib/uploadthing";
export function UploadActionDrawer(props: { showTrigger: boolean }) {
const bottomSheetModalRef = useRef<BottomSheetModal>(null);

const utils = trpc.useUtils();
const queryClient = useQueryClient();
const router = useRouter();

const imageUploader = useImageUploader("videoAndImage", {
Expand All @@ -26,7 +27,7 @@ export function UploadActionDrawer(props: { showTrigger: boolean }) {
Alert.alert("Upload Error", e.data?.reason ?? e.message);
},
onClientUploadComplete: (files) => {
utils.getFiles.invalidate();
queryClient.invalidateQueries(trpc.getFiles.queryFilter());

if (files.length === 1) {
// Auto-open the file if there's only one
Expand All @@ -46,7 +47,7 @@ export function UploadActionDrawer(props: { showTrigger: boolean }) {
Alert.alert("Upload Error", e.data?.reason ?? e.message);
},
onClientUploadComplete: (files) => {
utils.getFiles.invalidate();
queryClient.invalidateQueries(trpc.getFiles.queryFilter());

if (files.length === 1) {
// Auto-open the file if there's only one
Expand Down
63 changes: 27 additions & 36 deletions examples/minimal-expo/lib/trpc.tsx
Original file line number Diff line number Diff line change
@@ -1,24 +1,44 @@
import { useState } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { httpBatchLink, loggerLink } from "@trpc/client";
import { createTRPCReact } from "@trpc/react-query";
import { QueryClient } from "@tanstack/react-query";
import { createTRPCClient, httpBatchLink } from "@trpc/client";
import { inferRouterOutputs } from "@trpc/server";
import { createTRPCOptionsProxy } from "@trpc/tanstack-react-query";
import Constants from "expo-constants";

import type { TRPCRouter } from "../app/api/trpc/[trpc]+api";

export const queryClient = new QueryClient({
defaultOptions: {
queries: {
// ...
},
},
});

/**
* A set of typesafe hooks for consuming your API.
* A type-safe proxy for working with the React Query client.
*/
export const trpc = createTRPCReact<TRPCRouter>();
export const trpc = createTRPCOptionsProxy<TRPCRouter>({
client: createTRPCClient({
links: [
// loggerLink({
// enabled: (opts) =>
// process.env.NODE_ENV === "development" ||
// (opts.direction === "down" && opts.result instanceof Error),
// colorMode: "ansi",
// }),
httpBatchLink({ url: resolveUrl() }),
],
}),
queryClient,
});

export type RouterOutputs = inferRouterOutputs<TRPCRouter>;

/**
* Extend this function when going to production by
* setting the baseUrl to your production API URL.
*/
const resolveUrl = () => {
function resolveUrl() {
/**
* Gets the IP address of your host-machine. If it cannot automatically find it,
* you'll have to manually set it. NOTE: Port 3000 should work for most but confirm
Expand All @@ -41,33 +61,4 @@ const resolveUrl = () => {
`Failed to resolve URL from ${process.env.EXPO_PUBLIC_SERVER_ORIGIN} or ${debuggerHost}`,
);
}
};

/**
* A wrapper for your app that provides the TRPC context.
* Use only in _app.tsx
*/
export function TRPCProvider(props: { children: React.ReactNode }) {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
links: [
// loggerLink({
// enabled: (opts) =>
// process.env.NODE_ENV === "development" ||
// (opts.direction === "down" && opts.result instanceof Error),
// colorMode: "ansi",
// }),
httpBatchLink({ url: resolveUrl() }),
],
}),
);

return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{props.children}
</QueryClientProvider>
</trpc.Provider>
);
}
6 changes: 3 additions & 3 deletions examples/minimal-expo/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@
"@gorhom/bottom-sheet": "^4.6.1",
"@shopify/flash-list": "1.6.4",
"@tanstack/react-query": "^5.29.2",
"@trpc/client": "11.0.0-rc.452",
"@trpc/react-query": "11.0.0-rc.452",
"@trpc/server": "11.0.0-rc.452",
"@trpc/client": "11.0.0-rc.772",
"@trpc/server": "11.0.0-rc.772",
"@trpc/tanstack-react-query": "11.0.0-rc.772",
"@uploadthing/expo": "7.2.2",
"expo": "~51.0.8",
"expo-dev-client": "~4.0.10",
Expand Down
Loading

0 comments on commit 02a800c

Please sign in to comment.