-1

I am trying to implement my api into my webpage so i can use this frontend as interface to access the api.

I have created files namely api.js for the api:

// src/api.js
import axios from 'axios';

const api = axios.create({
  baseURL: 'http://localhost:8080', // Your API's base URL
  headers: {
    'Content-Type': 'application/json',
  },
});

export const getAllCustomers = () => api.get('/customers');
// Add other API functions as needed

api.d.ts for the module:

// src/api.d.ts
interface Customer {
    id: number;
    firstName: string;
    lastName: string;
    mobileNo: string;
    state: string;
    city: string;
    email: string;  
  }
  
  declare module './api' {
    export function getAllCustomers(): Promise<{ data: Customer[] }>;
    // Add other function declarations as needed
  }
  

server.js:

import express from 'express';
import cors from 'cors';
import api from './api'; // Adjust the path as necessary

const app = express();
const PORT = 8080;

app.use(cors());
app.use(express.json());

app.get('/customers', async (req, res) => {
  try {
    const response = await api.get('/customers'); // Use the API instance
    res.json(response.data); // Forward the API response to the client
  } catch (error) {
    res.status(500).json({ message: 'Error fetching customers', error: error.message });
  }
});

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

The file where i want to get all customer details, GetAllCustomerDetails.tsx:

import React, { useEffect, useState } from 'react';
import { getAllCustomers } from '../../api'; 

interface Customer {
  id: number;
  firstName: string;
  lastName: string;
  mobileNo: string;
  state: string;
  city: string;
  email: string;
}

const GetAllCustomerDetails: React.FC = () => {
  const [customers, setCustomers] = useState<Customer[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const fetchCustomers = async () => {
      try {
        const response = await getAllCustomers();
        setCustomers(response.data);
      } catch (error) {
        setError("Error fetching customer details");
      } finally {
        setLoading(false);
      }
    };

    fetchCustomers();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>{error}</div>;
  }

  return (
    <div>
      <h2>All Customers</h2>
      <ul>
        {customers.map((customer) => (
          <li key={customer.id}>
            <p>First Name: {customer.firstName}</p>
            <p>Last Name: {customer.lastName}</p>
            <p>Mobile No: {customer.mobileNo}</p>
            <p>State: {customer.state}</p>
            <p>City: {customer.city}</p>
            <p>Email: {customer.email}</p>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default GetAllCustomerDetails;

I am getting an error in importing the api in the GetAllCustomerDetails.tsx file.

The error is :

File 'd:/Courses/React/TEST-2/api-frontend/src/api.d.ts' is not a module.ts(2306)

This is my tsconfig.app.json and tsconfig.node.json respectively:

{
  "compilerOptions": {
    "composite": true,
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
    "target": "ES2015",
    "useDefineForClassFields": true,
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "module": "ES6",
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "moduleDetection": "force",
    "noEmit": true,
    "jsx": "react",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "baseUrl": "src",
    "paths": {
      "*": ["*"]
    },

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true
  },
  "include": ["src/**/*"]
}
{
  "compilerOptions": {
    "composite": true,
    "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
    "skipLibCheck": true,
    "module": "ESNext",
    "moduleResolution": "bundler",
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "noEmit": true
  },
  "include": ["vite.config.ts"]
}

I have tried to change the module to commonjs and the target to es6, but the error is not getting resolved.

1 Answer 1

0

This isnt a solution the above but we can just call the url of the api endpoint for the required. I have done the same and it is working for me now

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.