I used useEffect to fetch data, Is it wrong ?
Unanswered
Northeast Congo Lion posted this in #help-forum
Northeast Congo LionOP
"use client"
import React, { useEffect, useState } from "react";
import { useUser } from "@clerk/nextjs";
import axios from "axios";
type AdType = {
image: string;
link: string;
}
const Dashboard = () => {
const { user } = useUser();
const userId = user?.id;
const [ads, setAds] = useState<AdType[]>([]);
const fetchAds = async () => {
try {
const res = await axios.get(`/api/advertisement/`, {
headers: {
userId,
}
});
const advertisementData = res?.data?.advertisement;
setAds(advertisementData);
} catch (error) {
console.log('Error in Dashboard fetchAds', error);
}
}
useEffect(() => {
fetchAds();
}, []);
return (
<div className="flex flex-wrap">
{ads.map((ad, index) => (
<div key={index} className="w-1/3 p-4">
<div className="bg-white p-4 shadow rounded-md">
<div className="mb-4 w-48 h-48">
{ad?.image ? (
<img src={ad?.image} alt="Ad" className="w-full h-full object-cover" />
) : (
<div>Error: Image not found</div>
)}
</div>
<div className="flex justify-between">
<button className="bg-blue-500 text-white font-bold py-2 px-4 rounded hover:bg-blue-600" >Edit</button>
</div>
</div>
</div>
))}
</div>
);
}
export default Dashboard;27 Replies
you're fetching your own api routes?
you should not do that: https://nextjs-faq.com/fetch-api-in-rsc
you shouldn't use client component to fech data at all IMO, then what's the point of using server components.
@averydelusionalperson you should not do that: https://nextjs-faq.com/fetch-api-in-rsc
This only applies to server side fetches
yeah IK
that's why I said the next line
@joulev Good to me, though it’s more recommended to use react-query or swr for client side fetching
Northeast Congo LionOP
my application is not big enough right now, so I avoid it
@joulev Good to me, though it’s more recommended to use react-query or swr for client side fetching
yeah, he kinda sent the message in another thread, where I was talking about why use server component for fetching data instead of client fetch. So I assumed he wanted to use server side fetching.
@averydelusionalperson yeah, he kinda sent the message in another thread, where I was talking about why use server component for fetching data instead of client fetch. So I assumed he wanted to use server side fetching.
Northeast Congo LionOP
but I read that if want to fetch data then there is not need for server compnent, cause its mostly use to send data
I mean post request
you are confusing server actions for server components
both are different
@averydelusionalperson you are confusing server actions for server components
Northeast Congo LionOP
I will share my code, review it
I see the above code tho
all I am saying is if you're using next.js 13 app dir, and fetching using client side using
useEffect even if you can use server components.I don't see why
Northeast Congo LionOP
action file
route.ts
export async function fetchAds(clerkId: string){
try{
await connectDB();
const Ads = await Advertisement.find({clerkId});
if(!Ads){
throw new Error('Advertisement Not Found');
}
return JSON.parse(JSON.stringify(Ads));
}catch(error){
console.log('Error while fetching Ads:', error);
handleError(error);
}
}route.ts
export async function GET(req: Request){
try{
const url = new URL(req.url);
const userId = url.searchParams.get('userId');
// const userId = req.headers.get('userId')
const Ads = await fetchAds(userId!)
return NextResponse.json({message: 'Ads Fetch Successfully', advertisement:Ads})
}catch(error){
console.log('Error in Fetch Ads Get:', error);
handleError(error);
}
}@averydelusionalperson Either action file or api route can be removed
Northeast Congo LionOP
I will got with route
and add that action code in route file ?
@averydelusionalperson Either action file or api route can be removed
Northeast Congo LionOP
Is this ok ?
export async function GET(req: Request){
try{
const url = new URL(req.url);
const userId = url.searchParams.get('userId');
const clerkId = userId;
// const userId = req.headers.get('userId')
// const Ads = await fetchAds(userId!)
await connectDB();
const Ads = await Advertisement.find({clerkId});
if(!Ads){
throw new Error('Advertisement Not Found');
}
// return JSON.parse(JSON.stringify(Ads));
return NextResponse.json({message: 'Ads Fetch Successfully', advertisement:Ads})
}catch(error){
console.log('Error in Fetch Ads Get:', error);
handleError(error);
}
}yeah, it is
@averydelusionalperson yeah, it is
Northeast Congo LionOP
but bro, why need only one I mean server action or route file for GET method in Next