I use a server action for data fetching, and it should return data to the client component, but it’s not working as expected.
Server action:
"use server";
import { getCookies } from "next-client-cookies/server";
export async function getData() {
const cookie = getCookies();
const token = cookie.get("access_token");
const response = await fetch(url,{method: "GET", headers: {"Token" : token}});
const data = await response.json();
return data;
}
Client component:
"use client";
export default function Component() {
useEffect(() => {
async function getDataFromServerAction() {
const data = await getData();
console.log(data); //nothing out
}
})
}
I try to remove "use server". It works but cannot get cookie.
2
Answers
You are not calling the function you defined in the
useEffect
hook:You can read more about server actions and mutations in the docs.
I think, your useEffect misses dependency array.
You can edit your client component