API

Using API client

How to use API client to interact with the API.

In mobile app code, you can only access the API client from the client-side.

When you create a new component or screen and want to fetch some data, you can use the API client to do so.

Creating a client

We're creating a client-side API client in apps/mobile/src/lib/api/trpc.tsx file. It's a simple wrapper around the @tanstack/react-query that fetches or mutates data from the API.

It also requires wrapping your app in a TRPCReactProvider component to provide the API client to the rest of the app:

_layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <TRPCProvider>
      <SafeAreaProvider>
        <Stack>
          ...
          <Stack.Screen name="index" />
          ...
        </Stack>
        <StatusBar barStyle="light-content" />
      </SafeAreaProvider>
    </TRPCProvider>
  );
}

Ensure correct API url

Inside the apps/mobile/src/lib/api/trpc.tsx we're calling a function to get base url of your api, so make sure it's set correctly (especially on production) and your web api endpoint is corresponding with the name there.

trpc.tsx
const getBaseUrl = () => {
  /**
   * 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
   * you don't have anything else running on it, or you'd have to change it.
   *
   * **NOTE**: This is only for development. In production, you'll want to set the
   * baseUrl to your production API URL.
   */
  const debuggerHost = Constants.expoConfig?.hostUri;
  const localhost = debuggerHost?.split(":")[0];
 
  if (!localhost) {
    console.warn("Failed to get localhost. Pointing to production server...");
    return env.EXPO_PUBLIC_SITE_URL;
  }
  return `http://${localhost}:3000`;
};

As you can see we're relying on your machine IP address for local development (in case you want to open the app from another device) or on the environment variables in production to get it, so there shouldn't be any issues with it, but in case, please be aware where to find it 😉

Queries

Of course, everything comes already configured for you, so you just need to start using api in your components/screens.

For example, to fetch the list of posts you can use the useQuery hook:

app/(tabs)/tab-one.tsx
"use client";
 
import { api } from "~/lib/api/trpc";
 
export default function TabOneScreen() {
  const { data: posts, isLoading } = api.posts.getAll.useQuery();
 
  if (isLoading) {
    return <Text>Loading...</Text>;
  }
 
  /* do something with the data... */
  return (
    <View>
      <Text>{JSON.stringify(posts)}</Text>
    </View>
  );
}

It's using the same useQuery API as @tanstack/react-query, so you shouldn't have any troubles with it.

Mutations

If you want to perform a mutation in your mobile code, you can use the useMutation hook that comes straight from the integration with Tanstack Query:

form.tsx
import { api } from "~/lib/api/trpc";
 
export function CreatePost() {
  const utils = api.useUtils();
  const { mutate } = api.posts.create.useMutation({
    onSuccess: () => {
      toast.success("Post created successfully!");
      utils.posts.getAll.invalidate();
    },
  });
 
  return (
    <Form>
      <Button onPress={handleSubmit(mutate)}>Submit</Button>
    </Form>
  );
}

Here, we're also invalidating the query after the mutation is successful. This is a very important step to make sure that the data is updated in the UI.

Last updated on

On this page

Ship your startup everywhere. In minutes.