Data fetching for shadcn datatable in nextjs using axios

281 views Asked by At

so I'm working on a website using NextJS 14 and shadcn ui, along with prisma and axios, I'm trying to display a datatable but it's not working, it's returning a connection refused error and unhandled runtime error, I've tried searching all around for solutions but none seem to have solved it,

import Link from 'next/link';
import axios from 'axios';
import { Warga, columns } from './columns';
import { DataTable } from './data-table';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
import {
  Menubar,
  MenubarContent,
  MenubarItem,
  MenubarMenu,
  MenubarSeparator,
  MenubarTrigger,
} from '@/components/ui/menubar';
import { AlignRight } from 'lucide-react';

async function getData(): Promise<Warga[]> {
  // Fetch data from your API here.
  const res = await axios.get('/api/data');
  return res.data;
}

export default async function DataPage() {
  const data = await getData();
  return (
    <>
      <div className='container mx-auto my-8 flex-col md:flex'>
        {/* Header */}
        {/* Content */}
        <div className='flex-1 space-y-4 md:p-8 pt-6'>
          <Tabs
            defaultValue='rt01'
            className='space-y-4'
          >
            <TabsList>
              <TabsTrigger value='rt01'>RT 01</TabsTrigger>
              <TabsTrigger value='rt02'>RT 02</TabsTrigger>
              <TabsTrigger value='rt03'>RT 03</TabsTrigger>
              <TabsTrigger value='rt04'>RT 04</TabsTrigger>
            </TabsList>
            {/* Overview tab */}
            <TabsContent
              value='rt01'
              className='space-y-4'
            >
              <DataTable
                columns={columns}
                data={data}
              />
            </TabsContent>
          </Tabs>
        </div>
      </div>
    </>
  );
}

this is the error message

⨯ Error: connect ECONNREFUSED ::1:80
    at RedirectableRequest.emit (node:events:514:28)
    at ClientRequest.emit (node:events:514:28)
    at Socket.socketErrorListener (node:_http_client:501:9)
    at Socket.emit (node:events:514:28)
Cause: Error: connect ECONNREFUSED ::1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1495:16)   
    at TCPConnectWrap.callbackTrampoline (node:internal/async_hooks:130:17) {
  errno: -4078,
  code: 'ECONNREFUSED',
  syscall: 'connect',
  address: '::1',
  port: 80
}
 ⨯ Error: connect ECONNREFUSED ::1:80
    at RedirectableRequest.emit (node:events:514:28)
    at ClientRequest.emit (node:events:514:28)
    at Socket.socketErrorListener (node:_http_client:501:9)
    at Socket.emit (node:events:514:28)
digest: "4211328916"

and this is the api route handler

import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import type { Warga } from '@prisma/client';
const prisma = new PrismaClient();

export const GET = async (request: Request) => {
  const wargaData = await prisma.warga.findMany();
  return NextResponse.json(wargaData);
};

can anyone help me out? tia

1

There are 1 answers

1
stonith404 On BEST ANSWER

As your DataPage component runs on the server, Axios is unaware of the host for the HTTP request. Consequently, the call axios.get('/api/data') defaults to making a request to http://localhost/api/data.

You could append the host to the URL by doing the following:

import { headers } from 'next/headers';

async function getData(): Promise<Warga[]> {
  const host = headersList.get('host')
  // Fetch data from your API here.
  const res = await axios.get(`${host}/api/data`);
  return res.data;
}

But as DataPage is a server component you could directly query the database from the component, hereby completely eliminating the need for the route handler:

async function getData(): Promise<Warga[]> {
  // Query data directly from Prisma
  return await prisma.warga.findMany(); // <-- You will have to define the Prisma client in a seperate file
}