Skip to content

Instantly share code, notes, and snippets.

@cmnstmntmn
Last active December 8, 2024 15:51
Show Gist options
  • Select an option

  • Save cmnstmntmn/6edd8c7ef49b104ba00940350768a0fe to your computer and use it in GitHub Desktop.

Select an option

Save cmnstmntmn/6edd8c7ef49b104ba00940350768a0fe to your computer and use it in GitHub Desktop.
qwik server actions
import { component$, Resource, useResource$ } from "@builder.io/qwik";
import { serverGreeter } from "~/server/actions/public";
import { getGreeting } from "~/server/actions/protected";
export const Header = component$(() => {
const userDataResource = useResource$(
async () => await getGreeting({ name: "Pif" }),
);
return (
<section>
<Resource
value={userDataResource}
onPending={() => <div>Loading user profile...</div>}
onResolved={(userData) => <div>User data: {userData.name}</div>}
onRejected={(error) => (
<div>
Failed to load user data.{" "}
<pre>{JSON.stringify(error.message, null, 2)}</pre>
</div>
)}
/>
</section>
);
});
import { server$ } from "@builder.io/qwik-city";
export const getGreeting = server$(async function (input: { name: string }) {
const isAuthenticated = !!this.sharedMap.get("session");
if (!isAuthenticated) {
throw new Error("Unauthorized: You must be authenticated.");
}
console.log("Executing getGreeting with", input);
return { name: `Hello, ${input.name}` };
});
export const getGreeting2 = server$(async function (input: { name: string }) {
const isAuthenticated = !!this.sharedMap.get("session");
if (!isAuthenticated) {
throw new Error("Unauthorized: You must be authenticated.");
}
console.log("Executing getGreeting with", input);
return { name: `Hello, ${input.name}` };
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment