Skip to content

Instantly share code, notes, and snippets.

@maxsei
Created April 13, 2024 15:08
Show Gist options
  • Select an option

  • Save maxsei/43bb28c2ff27781d2aa68abf533c9c3e to your computer and use it in GitHub Desktop.

Select an option

Save maxsei/43bb28c2ff27781d2aa68abf533c9c3e to your computer and use it in GitHub Desktop.
quik todo component
import { component$ } from "@builder.io/qwik";
import {
type DocumentHead,
routeLoader$,
routeAction$,
zod$,
z,
Form,
} from "@builder.io/qwik-city";
import styles from "./todolist.module.css";
interface ListItem {
text: string;
}
export const useListLoader = routeLoader$(async (req) => {
const res = await req.platform.env.DB.prepare(
"SELECT text from todos;",
).all();
return res.results;
});
export const useAddToListAction = routeAction$(
async (item, req) => {
const id = crypto.randomUUID();
await req.platform.env.DB.prepare(
"INSERT INTO todos (id, text) VALUES(?, ?);",
)
.bind(id, item.text)
.run();
return {
success: true,
};
},
zod$({
text: z.string().trim().min(1),
}),
);
export default component$(() => {
const list = useListLoader();
const action = useAddToListAction();
return (
<>
<div class="container container-center">
<h1>
<span class="highlight">TODO</span> List
</h1>
</div>
<div role="presentation" class="ellipsis"></div>
<div class="container container-center">
{list.value.length === 0 ? (
<span class={styles.empty}>No items found</span>
) : (
<ul class={styles.list}>
{list.value.map((item, index) => (
<li key={`items-${index}`}>{item.text}</li>
))}
</ul>
)}
</div>
<div class="container container-center">
<Form action={action} spaReset>
<input type="text" name="text" required class={styles.input} />{" "}
<button type="submit" class="button-dark">
Add item
</button>
</Form>
<p class={styles.hint}>
PS: This little app works even when JavaScript is disabled.
</p>
</div>
</>
);
});
export const head: DocumentHead = {
title: "Qwik Todo List",
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment