Using GET Method in hmm-api
Basic Usage
1. Import and Create API Client
import ApiClient from "hmm-api";
// Create an API client
const api = new ApiClient();
2. Simple GET Request
// Fetch users
const response = await api.get("/users");
// Check if request was successful
if (response.success) {
// Access the data
const users = response.data;
console.log(users);
} else {
// Handle any errors
console.error(response.error);
}
Advanced Usage
With Type Safety
// Define an interface for your data
interface User {
id: number;
name: string;
email: string;
}
// Typed GET request
const response = await api.get<User>("/users/1");
if (response.success) {
// TypeScript knows the exact shape of the data
const user = response.data;
console.log(user.name); // Fully typed!
}
Custom Options
Add Headers
const response = await api.get("/users", {
headers: {
"X-Custom-Header": "Some Value",
},
});
Control Error Toasts
// Disable error notifications for this request
const response = await api.get("/users", {
showErrorToast: false,
});
Add a Cleanup Function
const response = await api.get("/users", {
finally: () => {
// This runs after the request, whether it succeeds or fails
hideLoadingSpinner();
},
});
Full Example
import ApiClient from "hmm-api";
// Assuming you have a toast library configured
const api = new ApiClient({
toast: yourToastLibrary,
});
async function fetchUserProfile() {
// Get user profile
const response = await api.get<UserProfile>("/profile", {
headers: {
Authorization: `Bearer ${yourAuthToken}`,
},
showErrorToast: true,
});
if (response.success) {
displayProfile(response.data);
}
}
Quick Tips
- Always check
response.success
before usingresponse.data
- Use TypeScript generics for type-safe responses
- Configure global settings when creating the ApiClient
- Easily handle different types of errors