Skip to content

Instantly share code, notes, and snippets.

@dualjack
Created October 24, 2023 12:19
Show Gist options
  • Save dualjack/4b5758d9a4e96c675181c17297bf5ab2 to your computer and use it in GitHub Desktop.
Save dualjack/4b5758d9a4e96c675181c17297bf5ab2 to your computer and use it in GitHub Desktop.
Sveltekit fetch action wrapper
import type {ActionResult} from "@sveltejs/kit";
import {applyAction, deserialize} from "$app/forms";
export const fetchAction = async <Input, Output>(actionPath: string, data: Input): Promise<Output> => {
const result: ActionResult = await fetch(actionPath, {
method: 'POST',
headers: {
'x-sveltekit-action': 'true'
},
body: JSON.stringify(data)
}).then(v => v.text()).then(v => deserialize(v));
await applyAction(result);
if(result.type === 'success'){
return result.data as Output;
}
throw null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment