Basic Svelte
Introduction
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
Similarly, we can add handlers for other HTTP verbs. Add a /todo/[id]
route by creating a src/routes/todo/[id]/+server.js
file with PUT
and DELETE
handlers for toggling and removing todos, using the toggleTodo
and deleteTodo
functions in src/lib/server/database.js
:
src/routes/todo/[id]/+server
import * as database from '$lib/server/database.js';
export async function PUT({ params, request, cookies }) {
const { done } = await request.json();
const userid = cookies.get('userid');
await database.toggleTodo({ userid, id: params.id, done });
return new Response(null, { status: 204 });
}
export async function DELETE({ params, cookies }) {
const userid = cookies.get('userid');
await database.deleteTodo({ userid, id: params.id });
return new Response(null, { status: 204 });
}
Since we don’t need to return any actual data to the browser, we’re returning an empty Response with a 204 No Content status.
We can now interact with this endpoint inside our event handlers:
src/routes/+page
<label>
<input
type="checkbox"
checked={todo.done}
onchange={async (e) => {
const done = e.currentTarget.checked;
await fetch(`/todo/${todo.id}`, {
method: 'PUT',
body: JSON.stringify({ done }),
headers: {
'Content-Type': 'application/json'
}
});
}}
/>
<span>{todo.description}</span>
<button
aria-label="Mark as complete"
onclick={async (e) => {
await fetch(`/todo/${todo.id}`, {
method: 'DELETE'
});
const todos = data.todos.filter((t) => t !== todo);
data = { ...data, todos };
}}
></button>
</label>
previous next
<script>
let { data } = $props();
</script>
<div class="centered">
<h1>todos</h1>
<label>
add a todo:
<input
type="text"
autocomplete="off"
onkeydown={async (e) => {
if (e.key !== 'Enter') return;
const input = e.currentTarget;
const description = input.value;
const response = await fetch('/todo', {
method: 'POST',
body: JSON.stringify({ description }),
headers: {
'Content-Type': 'application/json'
}
});
const { id } = await response.json();
const todos = [...data.todos, {
id,
description
}];
data = { ...data, todos };
input.value = '';
Yikes!
We couldn't start the app. Please ensure third party cookies are enabled for this site.