S
SolidJS3mo ago
gsoutz

"use server" doesn't work if put at the top of the file

I have this code which causes reactive triggers when user is changed by an useAction:
import { cache } from "@solidjs/router";
import { useSession } from "vinxi/http";
import { create_user, drop_user_by_id, new_user, Profile, profile_by_username, User, user_by_id } from "./routes/db";

export type UserSession = {
user_id: string
}

export const getSession = async () => {
"use server"
return await useSession<UserSession>({
password: process.env.SESSION_SECRET ?? 'secret_hash_key_placeholder_32_keys'
})
}


export const getUser = cache(async (): Promise<User> => {
"use server"
const session = await getSession()
return user
}, 'get_user')
import { cache } from "@solidjs/router";
import { useSession } from "vinxi/http";
import { create_user, drop_user_by_id, new_user, Profile, profile_by_username, User, user_by_id } from "./routes/db";

export type UserSession = {
user_id: string
}

export const getSession = async () => {
"use server"
return await useSession<UserSession>({
password: process.env.SESSION_SECRET ?? 'secret_hash_key_placeholder_32_keys'
})
}


export const getUser = cache(async (): Promise<User> => {
"use server"
const session = await getSession()
return user
}, 'get_user')
but if I remove the "use server" from inside functions and place it at the top of the file, The getUser() doesn't reactive update anymore, it breaks.
4 Replies
Brendonovich
Brendonovich3mo ago
Moving use server to the top of the file fundamentally changes how getUser behaves - to get the same behaviour you'd need to do the cache wrapping in a separate file that's not use server so that it can still do its thing and be reactive on the client
gsoutz
gsoutzOP3mo ago
so cache wrapper is not just an optimization but a necessity to achieve reactivity. I will just leave the use server inside functions as before and move on. Does that sound ok my understanding?
Brendonovich
Brendonovich3mo ago
I’m not exactly sure what you mean by ‘achieve reactivity’, but you should be fine alright with keeping use server inside the functions
Madaxen86
Madaxen863mo ago
Put give an example what Brendonovich meant:
const fetchUser = () => {
"use server"
...
}
export const getUser = cache(fetchUser), 'get_user')
const fetchUser = () => {
"use server"
...
}
export const getUser = cache(fetchUser), 'get_user')
fetchUser is a server function but the cached function getUser is not. It will call the API endpoint that is automatically created to get the User and then put the data in the client "cache". By placing the "use server" on top of the file you make getUser a server function which breaks the functionality of the cache.
Want results from more Discord servers?
Add your server