Aidin53
Aidin53

Reputation: 733

can I use server actions as SWR fetcher?

I wanted to know if this method is optimal or not. Because I did not find any documentation about it.

example

a server action to get the current user information

actions/whoami.ts

"use server";

import { auth, prisma } from "@/lib/auth"; // next-auth config file

export default async function whoami(): Promis<User | null> {
    const session = await auth();

    if (!session?.user || !session.user.email) {
        return null;
    }

    const user = await prisma.user.findUnique({
        where: {
            email: session.user.email,
        },
    });

    return user;
}

use in client components:

export default function ClientPage() {
    const { data: user } = useSWR("whoami", whoami);

    console.log({ user }); // user is fully typed
    return "...";
}

use in server components:

export default async function ServerPage() {
    const user = await whoami();

    console.log({ user }); // user is fully typed
    return "...";
}

The is a very good method, why this is not documented in nextjs or swr docs ? (I did not found it)

Upvotes: 3

Views: 1410

Answers (1)

Edgar Mata
Edgar Mata

Reputation: 11

At least for NextJS 14 I have found some problems using server actions as fetcher, for some reason sometimes it didn't fetch data when changing the server action. Suppose that we have an

object DataSource<T> = {
    getRows: async (params: GetRowsParams<T>) => await serverAction(params.filter, params.sort, params.pagination);
}

Now we put it as useSWR(params, dataSource.getRows);

If I have a client component with this hook, and use it in two or more pages with different data source objects, the data could get stale and useSWR won't fetch for the new server action. It could be for several reasons, one of them could be the ID of server actions, suppose that we have two files: users.ts and schedules.ts, if both files have 4 server actions and we make an index.ts file exporting all of these server actions, it will find an error for server actions $$ACTION_1, $$ACTION_2, $$ACTION_3, $$ACTION_4, as NextJS assign these IDs for the server actions of each file, so, if the useSWR sees them in the same way, it won't detect changes on the fetcher and hence won't fetch new data. So I recommend to make the server action a regular function and put it in a route handler, then use the fetch API.

Upvotes: 0

Related Questions