Client component fetching
Unanswered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
Am I fetching in client component?
Should I do it in server side?
Any suggestion to improve my code?
Thanks for help!
Should I do it in server side?
Any suggestion to improve my code?
Thanks for help!
// app/profile/[id]/ClientProfile.tsx
'use client';
import React, { useState } from 'react';
import { Button } from "@/components/ui/button";
import QRCode from 'qrcode.react';
import { CustomerWithLoyaltyPass } from '@/hooks/getCustomer';
export default function ClientProfile({ initialCustomer }: ClientProfileProps ) {
const [customerInfo, setCustomerInfo] = useState<CustomerWithLoyaltyPass>(initialCustomer);
const [qrCodeData, setQRCodeData] = useState<string | null>(initialCustomer.loyaltyPass?.qrCode || null);
const [error, setError] = useState<string | null>(null);
const generateQRCode = async () => {
try {
const response = await fetch(`/api/loyalty/generate-qr`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ customerId: customerInfo.id }),
});
if (!response.ok) {
throw new Error('Failed to generate QR code');
}
const data = await response.json();
setQRCodeData(data.qrCode);
setCustomerInfo(prev => ({
...prev,
loyaltyPass: prev.loyaltyPass ? {
...prev.loyaltyPass,
qrCode: data.qrCode
} : null
}));
} catch (err) {
setError('Error generating QR code');
console.error(err);
}
};
return (
<div >
<h1 >Customer Profile</h1>
<div className="mt-4">
<h2 c>{customerInfo.name}</h2>
<p>{customerInfo.id}</p>
{qrCodeData && (
<div className="mt-4">
<h3 className="text-lg font-semibold mb-2">Loyalty Pass QR Code</h3>
<QRCode value={qrCodeData} size={200} />
</div>
)}
{customerInfo.loyaltyPass && (
<p>Total Stamps: {customerInfo.loyaltyPass.points}</p>
)}
</div>
</div>
);
}4 Replies
@B33fb0n3 one thing that you can and should do is to have a clientside fetching library like swr or react query. That will help you, to have even more control over your data
Northeast Congo LionOP
But, do you think my code legit? I’m newbie, and I read that for best practices is to fetch server-side.
@Northeast Congo Lion But, do you think my code legit? I’m newbie, and I read that for best practices is to fetch server-side.
For only clientside stuff it's fine, yea. However it would be better to render as much as possible serverside. If I see that right you can fetch and render everything that I see serverside and only pass the qr code to the QRCode component
@Northeast Congo Lion solved?