Last active
June 16, 2021 17:31
-
-
Save Lcfvs/332492a5c49211230bbf8dab343b707e to your computer and use it in GitHub Desktop.
a simple fetcher, based on actions
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 { 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) |
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
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