Skip to content

Instantly share code, notes, and snippets.

@Lcfvs
Last active June 16, 2021 17:31
Show Gist options
  • Save Lcfvs/332492a5c49211230bbf8dab343b707e to your computer and use it in GitHub Desktop.
Save Lcfvs/332492a5c49211230bbf8dab343b707e to your computer and use it in GitHub Desktop.
a simple fetcher, based on actions
import { resolve, text } from './fetcher.js'
const fetchText = event => resolve(event, [
fetch,
text,
data => console.log({ data })
])
document.querySelector('form')
.addEventListener('submit', fetchText)
document.querySelector('a')
.addEventListener('click', fetchText)
const empties = ['GET', 'HEAD']
const reducer = async (promise, action) =>
action(await promise)
const reduce = async (initialValue, actions) =>
actions.reduce(reducer, initialValue)
export const json = response => response.json()
export const text = response => response.text()
export const resolve = (event, [...actions] = []) => {
event.preventDefault()
const { target } = event
const { action, href, method = 'GET' } = target
return reduce( new Request(action ?? href, {
method,
...!empties.includes(method.toUpperCase()) && {
body: new FormData(form)
}
}), actions)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment