Skip to main content

Overview

The categoryService module provides methods to interact with the category endpoints of the Villa Buena E-Commerce API. It handles fetching all available product categories.

Base Configuration

The service uses the configured Axios instance from api.js:
import axios from "axios";

export const api = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
});

Methods

getAll()

Retrieves all available product categories from the API.
return
Promise<Array<string>>
Returns a promise that resolves to an array of category name strings

API Endpoint

GET /products/categories

Usage Example

import { categoryService } from './services/categoryService';

const categories = await categoryService.getAll();
console.log(categories);
// Output: ["electronics", "jewelery", "men's clothing", "women's clothing"]

Response Structure

categories
Array<string>
required
An array of category name strings

Example Response

[
  "electronics",
  "jewelery",
  "men's clothing",
  "women's clothing"
]
The API returns category names as lowercase strings. You may need to format them for display purposes in your UI.

Implementation Details

Source Code

Location: src/services/categoryService.js
import { api } from "./api";

export const categoryService = {
  getAll: async () => {
    const { data } = await api.get("/products/categories");
    return data;
  },
};

Key Features

  • Async/Await Pattern: Uses modern async/await syntax for cleaner asynchronous code
  • Data Extraction: Destructures the data property from Axios responses automatically
  • Centralized Configuration: Uses the shared api instance for consistent base URL and configuration
  • Lightweight: Simple, focused interface for category operations

Error Handling

The getAll() method can throw errors in the following scenarios:
  • Network failures
  • API server errors (5xx)
  • Invalid endpoints (4xx)
  • Timeout errors
It’s recommended to wrap service calls in try-catch blocks or use .catch() handlers:
import { categoryService } from './services/categoryService';

try {
  const categories = await categoryService.getAll();
  // Handle success
} catch (error) {
  if (error.response) {
    // The request was made and server responded with error status
    console.error('Server error:', error.response.status);
  } else if (error.request) {
    // The request was made but no response was received
    console.error('Network error: No response received');
  } else {
    // Something else happened
    console.error('Error:', error.message);
  }
}

Common Use Cases

1. Category Navigation Menu

Build a dynamic navigation menu based on available categories:
import { categoryService } from './services/categoryService';

const categories = await categoryService.getAll();
const navMenu = categories.map(cat => ({
  name: cat,
  link: `/products/category/${cat}`
}));

2. Category Filter Dropdown

Create a filter dropdown for product listings:
import { categoryService } from './services/categoryService';

const categories = await categoryService.getAll();
// Render <select> with categories as <option> elements

3. Category Validation

Validate user input against available categories:
import { categoryService } from './services/categoryService';

const categories = await categoryService.getAll();
const isValidCategory = (category) => categories.includes(category);

if (isValidCategory(userInput)) {
  // Proceed with filtering
} else {
  // Show error message
}

4. Pre-loading Categories

Load categories on application startup for better performance:
import { categoryService } from './services/categoryService';

// In your app initialization
let cachedCategories = null;

export async function getCategories() {
  if (!cachedCategories) {
    cachedCategories = await categoryService.getAll();
  }
  return cachedCategories;
}

Integration with Product Service

The Category Service is designed to work seamlessly with the Product Service:
import { categoryService } from './services/categoryService';
import { productService } from './services/productService';

// Get all categories
const categories = await categoryService.getAll();

// Fetch products for each category
const productsByCategory = {};
for (const category of categories) {
  productsByCategory[category] = await productService.getByCategory(category);
}

console.log(productsByCategory);
Use the category names returned by categoryService.getAll() as parameters for productService.getByCategory() to ensure consistency.

  • Product Service - Manage products and fetch by category
  • Base API Configuration (src/services/api.js)

Build docs developers (and LLMs) love