Display list of guests from the backend

This commit is contained in:
Manuel Bustillo 2024-08-11 15:09:33 +02:00
parent 231e33f76c
commit f10c246e1a

View File

@ -1,32 +1,32 @@
'use client' 'use client'
import { Guest } from '@/app/lib/definitions'; import { Guest } from '@/app/lib/definitions';
import { useState, Suspense } from 'react'; import { useState, Suspense, useEffect } from 'react';
export default function guestsTable() { export default function guestsTable() {
const url = "http://localhost:3001/guests.json"; const [guests, setGuests] = useState<Guest[]>([]);
const getData = (): Guest[] => { useEffect(() => {
var guests: Guest[] = []; if (guests.length > 0) {
fetch(url) return;
}
fetch("http://localhost:3001/guests.json")
.then((response) => response.json()) .then((response) => response.json())
.then((data) => { .then((data) => {
data.data.map((record: any) => { setGuests(data.data.map((record: any) => {
guests.push({ return ({
id: record.id, id: record.id,
name: record.attributes.name, name: record.attributes.name,
email: record.attributes.email, email: record.attributes.email,
}); });
}))
}); });
}); });
return guests;
}
const [guests, setGuests] = useState<Guest[]>(getData());
return ( return (
<div className="w-full relative overflow-x-auto shadow-md sm:rounded-lg"> <div className="w-full relative overflow-x-auto shadow-md sm:rounded-lg">
<p className="py-3">There are {guests.length} guests in the list</p>
<table className="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400"> <table className="w-full text-sm text-left rtl:text-right text-gray-500 dark:text-gray-400">
<thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400"> <thead className="text-xs text-gray-700 uppercase bg-gray-50 dark:bg-gray-700 dark:text-gray-400">
<tr> <tr>
@ -44,7 +44,7 @@ export default function guestsTable() {
<tbody> <tbody>
<Suspense fallback="<tr><td colspan=3> Loading data</td></tr>"> <Suspense fallback="<tr><td colspan=3> Loading data</td></tr>">
{guests.map((guest) => ( {guests.map((guest) => (
<tr className="bg-white border-b odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800"> <tr key={guest.id} className="bg-white border-b odd:bg-white odd:dark:bg-gray-900 even:bg-gray-50 even:dark:bg-gray-800">
<th scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white"> <th scope="row" className="px-6 py-4 font-medium text-gray-900 whitespace-nowrap dark:text-white">
{guest.name} {guest.name}
</th> </th>