Created
October 24, 2023 12:19
-
-
Save dualjack/4b5758d9a4e96c675181c17297bf5ab2 to your computer and use it in GitHub Desktop.
Sveltekit fetch action wrapper
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 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