Created
January 15, 2023 12:03
-
-
Save omar2205/3b1b347510b9b1aa239484423e0c3d11 to your computer and use it in GitHub Desktop.
Update status action - a toggle/switch action to send a form action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script lang="ts"> | |
import { updatestatus } from '$lib/UpdateStatus' | |
import type { PageData } from './$types' | |
export let data: PageData | |
</script> | |
{#each data.users as user} | |
<input | |
name="status" | |
type="checkbox" | |
class="toggle" | |
formaction="/admin?/updatestatus" | |
use:updatestatus={user.id} | |
/> | |
{/each} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { applyAction, deserialize } from '$app/forms' | |
import { invalidateAll } from '$app/navigation' | |
export function updatestatus(node: HTMLInputElement, id: string | number) { | |
const url = node.formAction | |
const controller = new AbortController() | |
const handleChange = async () => { | |
const data = new FormData() | |
data.append('id', id.toString()) | |
data.append('status', node.checked.toString()) | |
const res = await fetch(url, { | |
method: 'POST', | |
body: data, | |
signal: controller.signal, | |
}) | |
const result = deserialize(await res.text()) | |
if (result.type === 'success') await invalidateAll() | |
applyAction(result) | |
} | |
node.addEventListener('change', handleChange) | |
return { | |
destroy() { | |
node.removeEventListener('change', handleChange) | |
controller.abort() | |
}, | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment