Next.js Discord

Discord Forum

Easier way to get data from ServerAction in a client side component?

Unanswered
American Curl posted this in #help-forum
Open in Discord
American CurlOP
I have a page which you could choose which data want to see, that is why the user will click a button and then the page will call the sever for the data, so I using ServerAction (it is not good because it is for mutation (queued and no AbortSignal...) but ... I don't see other new way to do that, ofc I could use XHR).

So there is a better way to setTables with callTables then using useEffect+async unkown arrow?

import ControlPanel from './ControlPanel';

import { dbAdm, getTables } from '@/lib/db';

const callTables = async () => {
    'use server';

    return await getTables(dbAdm);
};

export type CallTables = typeof callTables;

export default function DbInfoPage() {
    return <ControlPanel {...{ callTables }} />;
}


'use client';

import { useEffect, useState } from 'react';
import { CallTables } from './page';

export default function ControlPanel({
    callTables,
}: {
    callTables: CallTables;
}) {
    const [tables, setTables] = useState<Awaited<ReturnType<CallTables>>>([]);

    useEffect(() => {
        (async () => {
            setTables(await callTables());
        })();
    }, [callTables, setTables]);

    return (
        <div>
            <h1>ControlPanel</h1>

            <h2>Tables</h2>
            <ul>
                {tables.map((table) => (
                    <li key={table.name}>{table.name}</li>
                ))}
            </ul>
        </div>
    );
}

0 Replies