I want to retrieve a data from my data.ts then create a function to generate a random result from my database
import { sql } from '@vercel/postgres';
import { Businesses } from './definitions';
export async function getBusinesses() {
try {
console.log("Fetching Businesess...");
const data = await sql<Businesses>`SELECT * FROM businesses`;
return data.rows;
} catch (error) {
console.error('Database Error:', error);
throw new Error('Failed to fetch businesses data.');
}
}
definition.ts:
export type Businesses = {
id: number;
name: string;
description: string;
address: string;
city: string;
state: string;
postal_code?: string;
country: string;
phone?: string;
email?: string;
website?: string;
created_at: string;
updated_at: string;
}
dashboard/page.tsx:
import { getBusinesses } from "../lib/data";
export default async function Dashboard() {
const businesses = await getBusinesses();
return (
<div>
<h1>Dashboard Page</h1>
<br></br>
<h3>List of Businesses</h3>
<ul>
{businesses.map((business) => (
<li key={business.id}>{business.name}</li>
))}
</ul>
{/* button to generate random result here */}
</div>
);
}
I tried to use useState and useEffect but I received error fetching the data from the database saying it can’t connect to my database while I didn’t make any changes on my database credentials.. Please help
New contributor
ammarthemartian is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.