Next.js Fetching API Data problem, from the client
Unanswered
Black Norwegian Elkhound posted this in #help-forum
Black Norwegian ElkhoundOP
Hello friends I'm trying to access data, which was sent from the API, the data is called from the client side and is successfully received on the client, but when I try to access the data, I'm unable to access the data array, can you guys please help me out
This is the code that i have written
This is the API code
export const GET = async (req, res) => {
try {
const photos = await UserModel.find();
return NextResponse.json({ photos });
} catch (error) {
console.log(error);
}
};
This is the code calling the API from the client side.
const getPhotos = async () => {
const { data } = await axios.get("/api/user");
return data.photos;
};
export default function Home() {
const photos = getPhotos();
console.log(photos);
// console.log(photos.map((data) => console.log(data)));
return (
<div className=" w-full h-full ">
{/* {data?.map((val) => (
<div>{console.log(val)}</div>
))} */}
</div>
);
}
And this is the result that I have recieved
I'm trying to access the PromiseResult array but I'm unable to
This is the code that i have written
This is the API code
export const GET = async (req, res) => {
try {
const photos = await UserModel.find();
return NextResponse.json({ photos });
} catch (error) {
console.log(error);
}
};
This is the code calling the API from the client side.
const getPhotos = async () => {
const { data } = await axios.get("/api/user");
return data.photos;
};
export default function Home() {
const photos = getPhotos();
console.log(photos);
// console.log(photos.map((data) => console.log(data)));
return (
<div className=" w-full h-full ">
{/* {data?.map((val) => (
<div>{console.log(val)}</div>
))} */}
</div>
);
}
And this is the result that I have recieved
I'm trying to access the PromiseResult array but I'm unable to
3 Replies
You can resolve this error by using the data fetching method you should normally use. Normally you fetch data insure server components. You don’t need any api and can pass the photos to your client component if needed. So fetch your data serverside (inside a server component) and pass it down to your client component if needed. If you just render default html, then you don’t need any client component 🙂
@Black Norwegian Elkhound
@Black Norwegian Elkhound
@Black Norwegian Elkhound solved?
@Black Norwegian Elkhound ?