Using the API Client to Call Backend Routes

This guide explains how to set up and use an apiClient to call APIs from your NestJS backend routes in a MatureStack application.

Calling a GET Route

Use the API client to call a GET endpoint from your backend:

// pages/example.tsx
import { useEffect, useState } from 'react';
import apiClient from '@/services/apiClient';

export default function ExamplePage() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await apiClient.get('/example'); // Call the /example endpoint
        setData(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }

    fetchData();
  }, []);

  return (
    <div>
      <h1 className="text-2xl font-bold">Example Data</h1>
      {data ? <pre>{JSON.stringify(data, null, 2)}</pre> : <p>Loading...</p>}
    </div>
  );
}

Calling a POST Route

To send data to your backend, use the post method:

// pages/create-task.tsx
import { useState } from 'react';
import apiClient from '@/lib/apiClient';

export default function CreateTaskPage() {
  const [title, setTitle] = useState('');
  const [description, setDescription] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();

    try {
      const response = await apiClient.post('/tasks', { title, description });
      console.log('Task created:', response.data);
    } catch (error) {
      console.error('Error creating task:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <input
        type="text"
        placeholder="Task Title"
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        className="w-full px-4 py-2 border rounded-md"
      />
      <textarea
        placeholder="Task Description"
        value={description}
        onChange={(e) => setDescription(e.target.value)}
        className="w-full px-4 py-2 border rounded-md"
      />
      <button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-md">
        Create Task
      </button>
    </form>
  );
}

Best Practices

  • Keep the baseURL in an environment variable for easy configuration
  • Use async/await for cleaner API calls
  • Handle errors gracefully and display user-friendly messages
MatureStack LogoBuilt with MatureStack