can we fetch data using server actions directly in our client components?
Answered
Almond stone wasp posted this in #help-forum
Almond stone waspOP
I want to fetch data from server actions in a client component, like it is done in route handlers for a GET request?
Answered by Ray
// action.ts
"user server"
async function serverAction(id: string) {
return prisma.product.findOne({ where: { id } });
}
// client-component.ts
"use client"
export function Client({ id }:{ id:string }) {
const [data, setData] = useState([]);
return (
<>
<button
onClick={async () => {
const data = await serverAction(id);
setData(data);
}}
>
Fetch data
</button>
</>
);
}like this
3 Replies
// action.ts
"user server"
async function serverAction(id: string) {
return prisma.product.findOne({ where: { id } });
}
// client-component.ts
"use client"
export function Client({ id }:{ id:string }) {
const [data, setData] = useState([]);
return (
<>
<button
onClick={async () => {
const data = await serverAction(id);
setData(data);
}}
>
Fetch data
</button>
</>
);
}like this
Answer
Almond stone waspOP
ohh, got it thanks ðŸ˜