Skip to content

Instantly share code, notes, and snippets.

@faddah
Created October 3, 2024 02:18
Show Gist options
  • Save faddah/ab5c8075ded73f4a8c863d448fc00491 to your computer and use it in GitHub Desktop.
Save faddah/ab5c8075ded73f4a8c863d448fc00491 to your computer and use it in GitHub Desktop.
Faddah's current src-actions-index.ts & src-pages-ideas.astro from the Astro Party course
import { defineAction, type SafeResult } from "astro:actions";
import { db, Idea } from "astro:db";
import { z } from "astro:content";
interface IdeaInput {
id: number;
text: string;
good: boolean;
}
interface Server {
ideas: {
save: ReturnType<typeof defineAction>;
};
handler: (input: FormData) => Promise<SafeResult<{ id: number; text: string; good: boolean; }, string>>;
queryString: string;
orThrow: (input: FormData) => Promise<SafeResult<{ id: number; text: string; good: boolean; }, string>>;
}
export const server: Server = {
ideas: {
save: defineAction({
accept: "form",
input: z.object({
id: z.number(),
text: z.string(),
good: z.coerce.boolean(),
}),
handler: async (input) => {
await db.insert(Idea).values(input);
return `Success! New ${input.good ? 'good' : 'bad'} idea added!`;
},
}),
},
}
---
import { actions } from "astro:actions";
import { db, Idea } from "astro:db";
import Layout from "../layouts/default.astro";
import IdeaList from "../components/idea-list.astro";
export const prerender: boolean = false;
interface Idea {
id: number;
text: string;
good: boolean;
}
const headTitle: string = "Ideas 💡";
const pageTitle: string = "💡 I'm The Idea Guy, Bay-bee!! 💡";
const ideas: Idea[] = await db.select().from(Idea);
---
<Layout headTitle={headTitle} pageTitle={pageTitle}>
<h1>{pageTitle}</h1>
<section class="idea-form box">
<form method="POST" action={actions.ideas.save}>
<label for="text">
<h3>Idea:</h3>
<input type="text" id="text" name="text" />
</label>
<fieldset>
<legend><h3>Is this Idea Any Good?</h3></legend>
<label for="yes">
<input type="radio" id="yes" name="good" value="true" />
Yes
</label>
<label for="no">
<input type="radio" id="no" name="good" value="false" />
No
</label>
</fieldset>
<button type="submit">Add Idea</button>
</form>
</section>
<section class="ideas-lists flex">
<IdeaList title="Good Ideas 💡" ideas={ideas.filter((idea) => idea.good)} />
<IdeaList title="Bad Ideas 💩" ideas={ideas.filter((idea) => !idea.good)} />
</section>
</Layout>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment