-
Hi there, I'm trying to wrap my head around Astro together with HTMX following this tutorial: There are two things I'm trying to understand:
This is a .gif of what is happening when I run the code: Below are the important parts of my source code. Maybe someone can give me a pointer? Thanks db.jsonContent is taken from https://jsonplaceholder.typicode.com/posts {
"posts": [
{
"id": 1,
"title": "Hello World",
"body": "This is a test post",
"userId": 1
}]
} index.astro---
import Layout from '../layouts/Layout.astro';
import { JSONFilePreset } from 'lowdb/node';
import type { Post } from '../types/common';
const defaultData = { posts: [] };
const db = await JSONFilePreset<{ posts: Post[] }>('db.json', defaultData);
await db.read();
const { posts } = db.data;
---
<Layout title="Welcome to Astro.">
<main>
<ul>
{
posts.map((post) => (
<li>
Posts: {post.title.substring(23)} id: {post.id}
<button
hx-confirm="Are you sure?"
hx-target="closest li"
hx-swap="outerHTML"
hx-delete={`/posts/${post.id}`}
>
Delete
</button>
</li>
))
}
</ul>
</main>
</Layout>
posts/[id].astro---
export const partial = true;
import { JSONFilePreset } from 'lowdb/node';
import type { Post } from '../../types/common';
// Read or create db.json
const defaultData = { posts: [] };
const db = await JSONFilePreset<{ posts: Post[] }>('db.json', defaultData);
await db.read();
const { id } = Astro.params;
if (id === undefined || isNaN(parseInt(id, 10))) {
return Astro.redirect('/404');
}
let post = db.data.posts.find((post) => post.id === parseInt(id, 10));
if (!post) return Astro.redirect('/404');
if (Astro.request.method === 'DELETE') {
console.log('DELETE request');
Astro.response.status = 204;
db.update((data) => {
data.posts = data.posts.filter((post) => post.id !== parseInt(id, 10));
});
}
---
<span>delete post</span> astro.config.mjsimport { defineConfig } from 'astro/config';
// https://astro.build/config
export default defineConfig({
output: 'server',
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Okay. Sorry. I just changed it to response code 200 and it works fine with no reload of the page and the li elements are swapped. Also https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE states that 204 is with no reponse and 200 with so everything is as it should be. |
Beta Was this translation helpful? Give feedback.
Okay. Sorry. I just changed it to response code 200 and it works fine with no reload of the page and the li elements are swapped. Also https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/DELETE states that 204 is with no reponse and 200 with so everything is as it should be.