How to use useSWR optimistic UI with Prisma and server actions?
Unanswered
Polar bear posted this in #help-forum
Polar bearOP
I'm playing around useSWR and its optimistic updates but I've encountered a problem when using it with prisma.
Prisma returns a single object but the useSWR mutate is expecting an array of all entries ( I think? )
Error is:
girlsActions.tsx
girls.tsx
Any ideas?
Prisma returns a single object but the useSWR mutate is expecting an array of all entries ( I think? )
Error is:
Argument of type '{ id: string; imie: string; wiek: number; }' is not assignable to parameter of type '{ id: string; imie: string; wiek: number; }[] | Promise<{ id: string; imie: string; wiek: number; }[] | undefined> | MutatorCallback<{ id: string; imie: string; wiek: number; }[]> | undefined'.ts(2345)
girlsActions.tsx
export async function createGirl({ name, age }: { name: string; age: number }) {
await new Promise((res) => setTimeout(res, 1000));
return await prisma.dziewczyna.create({
data: {
imie: name,
wiek: age,
},
});
}
girls.tsx
"use client";
import useSWR from "swr";
import useSWRMutation from "swr";
import { getGirls, createGirl } from "../actions/girlsActions";
import type { Dziewczyna } from "@/generated";
import { Button } from "@/components/ui/button";
export default function Girls() {
const { data: girls, mutate } = useSWR<Dziewczyna[]>("getGirls", getGirls);
if (!girls) return;
return (
<div className="flex flex-col gap-2">
<p>Girls:</p>
{girls.map((girl) => {
return (
<div key={girl.id}>
{girl.imie} - {girl.wiek}
</div>
);
})}
<Button
onClick={() => {
mutate(await createGirl({ age: 12, name: "julia" }), {
optimisticData: [...girls, { wiek: 12, imie: "julia", id: "000" }],
});
}}
>
Create new girl
</Button>
</div>
);
}
Any ideas?