Cant fetch data when turning client page into server page
Unanswered
Singapura posted this in #help-forum
SingapuraOP
Im trying to not to use "use client" everywhere in next. ive read the docs, but i just dont udnerstand what im missing and why i cant make something similiar to get serverSideProps
as shown in the screenshots ive tried stop using useEffect and try to fetch on the server but when i do that, users never load and i get returnt the loading component. it only works on the one with useEffect
as shown in the screenshots ive tried stop using useEffect and try to fetch on the server but when i do that, users never load and i get returnt the loading component. it only works on the one with useEffect
8 Replies
Horse guard wasp
first share your get usersAction too
SingapuraOP
import axios from "axios";
import { IUser } from "../types/User";
import prisma from "@/app/libs/prismadb"
import getSession from "./getSession";
export const getUsers = async (): Promise<IUser[]> => {
try {
const { data } = await axios.get("/api/users");
return data;
} catch (error) {
console.error("Error fetching users:", error);
return [];
}
};
import { IUser } from "../types/User";
import prisma from "@/app/libs/prismadb"
import getSession from "./getSession";
export const getUsers = async (): Promise<IUser[]> => {
try {
const { data } = await axios.get("/api/users");
return data;
} catch (error) {
console.error("Error fetching users:", error);
return [];
}
};
Giant panda
Don't fetch from your own route handlers in server-side components
Just run the logic directly
Especially if your underlying handler would perform auth checking etc. which doesn't work since you'd have no cookies
SingapuraOP
ive tried doing it directly but it only works with fetch not axios
Horse guard wasp
yeah....axios, swr or useEffect only work on the client side.....for server components you have to use fetch( ) api
@Singapura ive tried doing it directly but it only works with fetch not axios
Use cache() if you want to deduplicate any async functions