Here's a boilerplate for a React TypeScript app using Apollo GraphQL, Ant Design, and Hasura backend. The boilerplate includes:
- Apollo Client setup to connect to the Hasura backend.
- GraphQL queries and mutations for CRUD operations on the specified tables.
- Custom hooks for each of the CRUD operations.
- A sample component that demonstrates how to use the hooks to perform CRUD operations on the customer table.
- Apollo Provider setup in the main entry file.
Apollo Client Setup
First, set up the Apollo Client to connect to the Hasura backend. Create a file called apolloClient.ts:
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = createHttpLink({
uri: 'YOUR_HASURA_GRAPHQL_ENDPOINT',
});
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('token');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
}
}
});
const client = new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache(),
});
export default client;
GraphQL Queries and Mutations
Create a file called graphql.ts to hold all the GraphQL queries and mutations:
import { gql } from '@apollo/client';
// Customer Queries and Mutations
export const GET_CUSTOMERS = gql`
query GetCustomers {
customer {
id
name
email
}
}
`;
export const GET_CUSTOMER_BY_ID = gql`
query GetCustomerById($id: Int!) {
customer_by_pk(id: $id) {
id
name
email
}
}
`;
export const CREATE_CUSTOMER = gql`
mutation CreateCustomer($name: String!, $email: String!) {
insert_customer_one(object: {name: $name, email: $email}) {
id
name
email
}
}
`;
export const UPDATE_CUSTOMER = gql`
mutation UpdateCustomer($id: Int!, $name: String!, $email: String!) {
update_customer_by_pk(pk_columns: {id: $id}, _set: {name: $name, email: $email}) {
id
name
email
}
}
`;
export const DELETE_CUSTOMER = gql`
mutation DeleteCustomer($id: Int!) {
delete_customer_by_pk(id: $id) {
id
}
}
`;
// Repeat similar queries and mutations for other tables (employee, product, etc.)
Custom Hooks
Create a file called hooks.ts to hold all the custom hooks for CRUD operations:
import { useQuery, useMutation } from '@apollo/client';
import {
GET_CUSTOMERS,
GET_CUSTOMER_BY_ID,
CREATE_CUSTOMER,
UPDATE_CUSTOMER,
DELETE_CUSTOMER,
// Import other queries and mutations
} from './graphql';
// Customer Hooks
export const useCustomers = () => {
const { data, loading, error } = useQuery(GET_CUSTOMERS);
return { data: data?.customer, loading, error };
};
export const useCustomerById = (id: number) => {
const { data, loading, error } = useQuery(GET_CUSTOMER_BY_ID, {
variables: { id },
});
return { data: data?.customer_by_pk, loading, error };
};
export const useCreateCustomer = () => {
const [createCustomer, { data, loading, error }] = useMutation(CREATE_CUSTOMER);
return { createCustomer, data, loading, error };
};
export const useUpdateCustomer = () => {
const [updateCustomer, { data, loading, error }] = useMutation(UPDATE_CUSTOMER);
return { updateCustomer, data, loading, error };
};
export const useDeleteCustomer = () => {
const [deleteCustomer, { data, loading, error }] = useMutation(DELETE_CUSTOMER);
return { deleteCustomer, data, loading, error };
};
// Repeat similar hooks for other tables (employee, product, etc.)
Sample Component
Create a file called CustomerComponent.tsx to demonstrate how to use the hooks:
import React, { useState } from 'react';
import { Button, Table, Form, Input, Modal, message } from 'antd';
import { useCustomers, useCreateCustomer, useUpdateCustomer, useDeleteCustomer } from './hooks';
const CustomerComponent: React.FC = () => {
const { data: customers, loading, error } = useCustomers();
const { createCustomer } = useCreateCustomer();
const { updateCustomer } = useUpdateCustomer();
const { deleteCustomer } = useDeleteCustomer();
const [isModalVisible, setIsModalVisible] = useState(false);
const [form] = Form.useForm();
const [editingCustomer, setEditingCustomer] = useState<any>(null);
const showModal = () => {
setIsModalVisible(true);
};
const handleCancel = () => {
setIsModalVisible(false);
form.resetFields();
setEditingCustomer(null);
};
const handleCreate = async (values: any) => {
try {
await createCustomer({
variables: {
name: values.name,
email: values.email,
},
});
message.success('Customer created successfully');
handleCancel();
} catch (err) {
message.error('Failed to create customer');
}
};
const handleUpdate = async (values: any) => {
try {
await updateCustomer({
variables: {
id: editingCustomer.id,
name: values.name,
email: values.email,
},
});
message.success('Customer updated successfully');
handleCancel();
} catch (err) {
message.error('Failed to update customer');
}
};
const handleDelete = async (id: number) => {
try {
await deleteCustomer({
variables: { id },
});
message.success('Customer deleted successfully');
} catch (err) {
message.error('Failed to delete customer');
}
};
const handleEdit = (customer: any) => {
setEditingCustomer(customer);
form.setFieldsValue({
name: customer.name,
email: customer.email,
});
showModal();
};
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Email',
dataIndex: 'email',
key: 'email',
},
{
title: 'Actions',
key: 'actions',
render: (text: any, record: any) => (
<span>
<Button type="link" onClick={() => handleEdit(record)}>
Edit
</Button>
<Button type="link" danger onClick={() => handleDelete(record.id)}>
Delete
</Button>
</span>
),
},
];
return (
<div>
<Button type="primary" onClick={showModal} style={{ marginBottom: 16 }}>
Add Customer
</Button>
<Table dataSource={customers} columns={columns} loading={loading} rowKey="id" />
<Modal
title={editingCustomer ? 'Edit Customer' : 'Add Customer'}
visible={isModalVisible}
onCancel={handleCancel}
footer={null}
>
<Form form={form} onFinish={editingCustomer ? handleUpdate : handleCreate}>
<Form.Item name="name" label="Name" rules={[{ required: true, message: 'Please input the name!' }]}>
<Input />
</Form.Item>
<Form.Item name="email" label="Email" rules={[{ required: true, message: 'Please input the email!' }]}>
<Input />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit">
{editingCustomer ? 'Update' : 'Create'}
</Button>
</Form.Item>
</Form>
</Modal>
</div>
);
};
export default CustomerComponent;
Apollo Provider Setup
Set up the Apollo Provider in the main entry file of the app, usually index.tsx or App.tsx:
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/client';
import client from './apolloClient';
import App from './App';
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
Sample App Component
Create a simple App component that includes the CustomerComponent:
import React from 'react';
import CustomerComponent from './CustomerComponent';
const App: React.FC = () => {
return (
<div style={{ padding: 24 }}>
<h1>Customer Management</h1>
<CustomerComponent />
</div>
);
};
export default App;
This boilerplate provides a solid foundation for building a full-featured CRUD application with React, TypeScript, Apollo GraphQL, and Ant Design. You can extend it by adding more complex queries and mutations as needed.