image

Jun 07 2023

cover

Creating a TypeScript React Class Service for CRUD Operations using Axios

In this tutorial, we will learn how to create a TypeScript React service to perform CRUD (Create, Read, Update, Delete) operations using the Axios library. We will build a service class that encapsulates the HTTP requests to a mock API and use it in a React component to manage data.



Creating the DataService Class

In this step, we will create a DataService class that handles the CRUD operations using Axios and TypeScript.


Create a new file called DataService.ts in the src folder, and add the following code to it:


import axios, { AxiosResponse } from 'axios';

const BASE_URL = 'https://api.example.com'; // Replace with your API endpoint

interface Data {
id: number;
// Add your data properties here
}

class DataService {
// Function to fetch data
async fetchData(): Promise<Data[]> {
try {
const response: AxiosResponse<Data[]> = await axios.get(`${BASE_URL}/data`);
return response.data;
} catch (error) {
console.error('Error fetching data:', error);
throw error;
}
}

// Function to create data
async createData(newData: Data): Promise<Data> {
try {
const response: AxiosResponse<Data> = await axios.post(`${BASE_URL}/data`, newData);
return response.data;
} catch (error) {
console.error('Error creating data:', error);
throw error;
}
}

// Function to update data
async updateData(id: number, updatedData: Data): Promise<Data> {
try {
const response: AxiosResponse<Data> = await axios.put(`${BASE_URL}/data/${id}`, updatedData);
return response.data;
} catch (error) {
console.error('Error updating data:', error);
throw error;
}
}

// Function to delete data
async deleteData(id: number): Promise<void> {
try {
await axios.delete(`${BASE_URL}/data/${id}`);
} catch (error) {
console.error('Error deleting data:', error);
throw error;
}
}
}

export default DataService;

In the DataService class, we define methods for each CRUD operation using Axios to make HTTP requests to the mock API. We also define the Data interface to specify the structure of the data.


Using the DataService in a React Component

Now that we have our DataService class, let's use it in a React component to perform CRUD operations. Open the src/App.tsx file and replace its contents with the following code:


import { useState, useEffect } from 'react';
import DataService, { Data } from './DataService';

const dataService = new DataService();

const App = () => {
const [data, setData] = useState<Data[]>([]);

useEffect(() => {
// Fetch data on component mount
fetchAllData();
}, []);

const fetchAllData = async () => {
try {
const data = await dataService.fetchData();
setData(data);
} catch (error) {
// Handle error
}
};

const handleCreate = async (newData: Data) => {
try {
const createdData = await dataService.createData(newData);
setData([...data, createdData]);
} catch (error) {
// Handle error
}
};

const handleUpdate = async (id: number, updatedData: Data) => {
try {
const updated = await dataService.updateData(id, updatedData);
const updatedList = data.map(item => (item.id === id ? updated : item));
setData(updatedList);
} catch (error) {
// Handle error
}
};

const handleDelete = async (id: number) => {
try {
await dataService.deleteData(id);
const updatedList = data.filter(item => item.id !== id);
setData(updatedList);
} catch (error) {
// Handle error
}
};

return (
<div>
{/* Render your components here */}
</div>
);
};

export default App;


In the above code, we import the DataService class and create an instance of it called dataService. The useEffect hook is used to fetch data on component mount. The handleCreate, handleUpdate, and handleDelete functions make use of the corresponding methods from the dataService instance to perform the CRUD operations and update the state accordingly.


You can now extend this example by connecting it to a real API or integrating it with your existing TypeScript React application to perform CRUD operations.