5.9 KiB
Products API Integration
This document describes the integration of the Products API from https://trantran.zenstores.com.vn/api/Products into the React POS application.
Overview
The integration includes:
- Environment configuration for API base URL
- Axios-based API service layer
- Redux actions and reducers for state management
- Updated ProductList component with API integration
- Error handling and loading states
Files Created/Modified
New Files Created:
-
.env- Environment variablesREACT_APP_API_BASE_URL=https://trantran.zenstores.com.vn/api/ -
src/services/api.js- Main API configuration with axios- Base axios instance with interceptors
- Request/response logging
- Error handling
- Authentication token support
-
src/services/productsApi.js- Products API service- getAllProducts()
- getProductById(id)
- createProduct(productData)
- updateProduct(id, productData)
- deleteProduct(id)
- searchProducts(query)
- getCategories()
- getBrands()
- Bulk operations
-
src/core/redux/actions/productActions.js- Redux actions- Async actions for all CRUD operations
- Loading states management
- Error handling
-
src/core/redux/reducers/productReducer.js- Redux reducer- State management for products
- Loading and error states
- Search functionality
-
src/components/ApiTest.jsx- API testing component- Test API connectivity
- Debug API responses
Modified Files:
-
src/core/redux/reducer.jsx- Updated to use combineReducers- Added new product reducer
- Maintained backward compatibility with legacy reducer
-
src/feature-module/inventory/productlist.jsx- Enhanced with API integration- Fetches data from API on component mount
- Fallback to legacy data if API fails
- Loading states and error handling
- Real-time search functionality
- Delete confirmation with API calls
Usage
Environment Setup
-
Ensure the
.envfile is in the project root with:REACT_APP_API_BASE_URL=https://trantran.zenstores.com.vn/api/ -
Restart the development server after adding environment variables.
Using the API Service
import { productsApi } from '../services/productsApi';
// Get all products
const products = await productsApi.getAllProducts();
// Get product by ID
const product = await productsApi.getProductById(123);
// Create new product
const newProduct = await productsApi.createProduct({
name: 'Product Name',
price: 99.99,
// ... other fields
});
// Update product
const updatedProduct = await productsApi.updateProduct(123, {
name: 'Updated Name',
price: 149.99
});
// Delete product
await productsApi.deleteProduct(123);
Using Redux Actions
import { useDispatch, useSelector } from 'react-redux';
import { fetchProducts, createProduct, deleteProduct } from '../core/redux/actions/productActions';
const MyComponent = () => {
const dispatch = useDispatch();
const { products, loading, error } = useSelector(state => state.products);
// Fetch products
useEffect(() => {
dispatch(fetchProducts());
}, [dispatch]);
// Create product
const handleCreate = async (productData) => {
try {
await dispatch(createProduct(productData));
// Success handling
} catch (error) {
// Error handling
}
};
// Delete product
const handleDelete = async (productId) => {
try {
await dispatch(deleteProduct(productId));
// Success handling
} catch (error) {
// Error handling
}
};
return (
<div>
{loading && <div>Loading...</div>}
{error && <div>Error: {error}</div>}
{products.map(product => (
<div key={product.id}>{product.name}</div>
))}
</div>
);
};
API Endpoints
The integration supports the following endpoints:
GET /Products- Get all productsGET /Products/{id}- Get product by IDPOST /Products- Create new productPUT /Products/{id}- Update productDELETE /Products/{id}- Delete productGET /Products/search?q={query}- Search productsGET /Products/categories- Get categoriesGET /Products/brands- Get brands
Error Handling
The integration includes comprehensive error handling:
- Network Errors - Connection issues, timeouts
- HTTP Errors - 4xx, 5xx status codes
- Authentication Errors - 401 Unauthorized
- Validation Errors - Invalid data format
Errors are displayed to users with retry options where appropriate.
Testing
Use the ApiTest component to verify API connectivity:
import ApiTest from './components/ApiTest';
// Add to your router or render directly
<ApiTest />
Backward Compatibility
The integration maintains backward compatibility:
- Legacy Redux state structure is preserved
- Components fallback to static data if API fails
- Existing functionality continues to work
Next Steps
- Authentication - Add user authentication if required
- Caching - Implement data caching for better performance
- Pagination - Add pagination support for large datasets
- Real-time Updates - Consider WebSocket integration for live updates
- Offline Support - Add offline functionality with local storage
Troubleshooting
Common Issues:
- CORS Errors - Ensure the API server allows requests from your domain
- Environment Variables - Restart development server after changing .env
- Network Issues - Check API server availability
- Authentication - Verify API key/token if required
Debug Steps:
- Check browser console for errors
- Use the ApiTest component to verify connectivity
- Check Network tab in browser DevTools
- Verify environment variables are loaded correctly
Support
For issues related to the API integration, check:
- Browser console for error messages
- Network requests in DevTools
- Redux DevTools for state changes
- API server logs if accessible