Search code examples
javascriptnext.jsnextjs14

Next.js 14 Server Action Not Returning Data to Client-Side Component


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.


Solution

  • 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();
        },[]) 
        // Empty dependency array since effect doesn't depend on reactive values
    }
    

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