skip to Main Content

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


  1. You are not calling the function you defined in the useEffect hook:

    "use client";
    
    export default function Component() {
        useEffect(() => {
            async function getDataFromServerAction() {
                const data = await getData();
                console.log(data); //nothing out
            }
            // Call the above function
            getDataFromServerAction();
        },[]) 
        //modify dependency as per your requirements, empty array will call use effect atleast once
    }
    

    You can read more about server actions and mutations in the docs.

    Login or Signup to reply.
  2. I think, your useEffect misses dependency array.
    You can edit your client component

    "use client";
    
     export default function Component() {
        useEffect(() => {
            async function getDataFromServerAction() {
                const data = await getData();
                console.log(data); //nothing out
               }
            }, [])
     }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search