Skip to main content

Querying the API

To query the API in your application, you can use the Api object from @/core/trpc. This object provides a convenient way to interact with your API endpoints.

Using the Api object

First, import the Api object from @/core/trpc:

import { Api } from '@/core/trpc';

The Api object contains methods corresponding to your API endpoints. You can use these methods to make queries or mutations.

Making a Query

To make a query, use the appropriate method on the Api object. For example, to fetch users:

const { data, isLoading, error } = Api.users.findMany.useQuery();

This will return an object with the following properties:

  • data: The result of the query
  • isLoading: A boolean indicating if the query is still loading
  • error: Any error that occurred during the query

Making a Mutation

For mutations, use the useMutation hook:

const { mutateAsync: createUser } = Api.users.create.useMutation();

// Later in your code
await createUser({ name: 'John Doe', email: 'john@example.com' });

Example Usage

Here's a complete example of how you might use the Api object in a React component with Ant Design:

import React from 'react';
import { Api } from '@/core/trpc';
import { List, Button, Spin, message } from 'antd';

const UserList = () => {
const { data: users, isLoading, error } = Api.users.findMany.useQuery();
const { mutateAsync: createUser } = Api.users.create.useMutation();

if (isLoading) return <Spin />;
if (error) return <div>An error occurred: {error.message}</div>;

const handleCreateUser = async () => {
try {
await createUser({ name: 'John Doe', email: 'john@example.com' });
message.success('User created successfully');
} catch (err) {
message.error('Failed to create user');
}
};

return (
<div>
<List
dataSource={users}
renderItem={user => (
<List.Item key={user.id}>
{user.name}
</List.Item>
)}
/>
<Button onClick={handleCreateUser}>Create User</Button>
</div>
);
};

export default UserList;

This guide should help you get started with querying your API using the Api object from @/core/trpc and Ant Design components. Remember to adjust the examples according to your specific API structure and needs.