S
SolidJS•3mo ago
alrightsure

Top level "use server" doesn't seem to work

Hey all, I've noticed that I put "use server" at the top of the file, it doesn't seem to actually treat the functions in the file as server functions, and the actions don't work as expected. I wanted to ask here before filing an issue, as I feel like maybe I am misunderstanding. For example, this seems to work:
import { db } from "./db";
import { action, cache, revalidate } from "@solidjs/router";

export const getMessages = cache(async () => {
"use server";

const messages = await db.messages.findMany();
return messages;

}, "messages");

export const sendMessage = action(async ({ text }: { text: string }) => {
"use server";

await db.messages.create({
data: { text }
});

revalidate(getMessages.keyFor());
});
import { db } from "./db";
import { action, cache, revalidate } from "@solidjs/router";

export const getMessages = cache(async () => {
"use server";

const messages = await db.messages.findMany();
return messages;

}, "messages");

export const sendMessage = action(async ({ text }: { text: string }) => {
"use server";

await db.messages.create({
data: { text }
});

revalidate(getMessages.keyFor());
});
However, this throws an error when I try to call these functions:
"use server";

import { db } from "./db";
import { action, cache, revalidate } from "@solidjs/router";

export const getMessages = cache(async () => {
const messages = await db.messages.findMany();
return messages;

}, "messages");

export const sendMessage = action(async ({ text }: { text: string }) => {
await db.messages.create({
data: { text }
});

revalidate(getMessages.keyFor());
});
"use server";

import { db } from "./db";
import { action, cache, revalidate } from "@solidjs/router";

export const getMessages = cache(async () => {
const messages = await db.messages.findMany();
return messages;

}, "messages");

export const sendMessage = action(async ({ text }: { text: string }) => {
await db.messages.create({
data: { text }
});

revalidate(getMessages.keyFor());
});
Is this intended behavior?
4 Replies
Brendonovich
Brendonovich•3mo ago
These two examples aren't equivalent - use server files should only export raw functions, wrapping them in cache won't work and means that the cache won't exist on the client An equivalent form would be defining the async functions in one use server file and then exporting the cache-wrapped versions in a second non-use server file
alrightsure
alrightsureOP•3mo ago
ahhh ok. thanks!
brenelz
brenelz•3mo ago
Oh this is a good explanation. I just always use it inline instead of top level
Madaxen86
Madaxen86•3mo ago
Me too. Then I am sure nothing leaks 🥷
Want results from more Discord servers?
Add your server