Button partials with any methods

This commit is contained in:
2026-11-11 16:56:47 -03:00
parent 8400c019e0
commit 3866b47741
3 changed files with 417 additions and 15 deletions
+94
View File
@@ -219,6 +219,100 @@ Keep the following in mind when using other methods:
- **CSRF protection:** The [CSRF middleware](/docs/plugins/csrf) treats these
methods like `POST`, so they get the same checks.
### Sending requests from buttons
A `<button>` with an `f-partial` attribute also triggers a partial request on
its own. This applies to buttons outside a form and to buttons with
`type="button"`. Submit buttons inside a form submit the form instead, as
described above. By default, the button sends a `GET` request to the `f-partial`
URL and applies the partials in the response. Unlike links, buttons don't change
the URL in the address bar.
To use another method, add an `f-method` attribute. This is handy for actions
like deleting an item from a list, where wrapping each button in a `<form>`
would be awkward.
```tsx routes/todos.tsx
import { Partial } from "sweet/runtime";
import { define } from "../utils.ts";
export const handler = define.handlers({
async DELETE(ctx) {
const form = await ctx.req.formData();
await deleteTodo(String(form.get("id")));
return ctx.render(<TodoList todos={await getTodos()} />);
},
});
function TodoList(props: { todos: Todo[] }) {
return (
<Partial name="todos">
<ul>
{props.todos.map((todo) => (
<li key={todo.id}>
{todo.title}
<button
type="button"
f-partial="/todos"
f-method="DELETE"
name="id"
value={todo.id}
>
Delete
</button>
</li>
))}
</ul>
</Partial>
);
}
export default define.page(async () => {
const todos = await getTodos();
return (
<div f-client-nav>
<TodoList todos={todos} />
</div>
);
});
```
When `f-method` is set to something other than `GET`, the request body is
`multipart/form-data` and contains:
- the button's own `name` and `value`, if it has a `name`
- every field of the surrounding form, if the button is a `type="button"` inside
a `<form>`
A `GET` button doesn't send any data. Like with forms, you can write the method
in any case.
To ask for confirmation first, call `preventDefault()` on the click event in an
island. Fresh won't send the request when the event was cancelled.
```tsx islands/DeleteButton.tsx
export function DeleteButton(props: { id: string }) {
return (
<button
type="button"
f-partial="/todos"
f-method="DELETE"
name="id"
value={props.id}
onClick={(e) => {
if (!confirm("Delete this todo?")) e.preventDefault();
}}
>
Delete
</button>
);
}
```
[Loading indicators](#loading-indicators) work on these buttons too, and the
same advice about redirects applies. Buttons with `f-partial` rely on
JavaScript, so they do nothing if JavaScript isn't loaded.
## Sending multiple Partials at the same time
A neat aspect of partials in Fresh is that a response can return as many