Skip to content

Commit

Permalink
Fix: Add try catch statement to resolve build error
Browse files Browse the repository at this point in the history
  • Loading branch information
Ho-s committed Feb 19, 2024
1 parent d76b325 commit f5d56e4
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 13 deletions.
34 changes: 25 additions & 9 deletions src/app/cars/[detail]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,19 @@ import { API_HOST } from '~/constants/apiRelated';

import { Car } from '../page';

async function getCarDetail(detail: string): Promise<Car> {
const res = await fetch(API_HOST + `/api/cars/${detail}`);
return res.json();
async function getCarDetail(detail: string): Promise<Car | undefined> {
try {
const res = await fetch(API_HOST + `/api/cars/${detail}`);

if (!res.ok) {
throw new Error('Failed to fetch data');
}

return res.json();
} catch (e: any) {
console.log(e);
return undefined;
}
}

export default async function CarsDetailPage({
Expand All @@ -19,13 +29,19 @@ export default async function CarsDetailPage({

return (
<div className="cars-detail-page">
<Image src={car.driverAvatar} width={50} height={50} alt="driver-image" />
{car && (
<>
<Image src={car.driverAvatar} width={50} height={50} alt="driver-image" />

{Object.entries(car).map(([key, value]) => (
<p key={key}>
{key}: <span>{value}</span>
</p>
))}
<>
{Object.entries(car).map(([key, value]) => (
<p key={key}>
{key}: <span>{value}</span>
</p>
))}
</>
</>
)}
<button>
<Link href="/cars">Go back to list</Link>
</button>
Expand Down
18 changes: 14 additions & 4 deletions src/app/cars/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,20 @@ export interface Car {
}

async function getCars(): Promise<Car[]> {
// You need to set base url in .env as origin of your url
const res = await fetch(API_HOST + '/api/cars');
await new Promise(resolve => setTimeout(resolve, 4000));
return res.json();
try {
// You need to set base url in .env as origin of your url
const res = await fetch(API_HOST + '/api/cars');

if (!res.ok) {
throw new Error('Failed to fetch data');
}

await new Promise(resolve => setTimeout(resolve, 4000));
return res.json();
} catch (e: any) {
console.error(e);
return [];
}
}

export default async function CarsPage() {
Expand Down

0 comments on commit f5d56e4

Please sign in to comment.