Closed alex-dixon closed 5 years ago
@framework-x/fetch-fx
import * as R from 'ramda' const keys = ['body', 'bodyUsed', 'ok', 'status', 'statusText', 'headers', 'redirected', 'url', 'type'] const fetchFx = R.curry(({dispatch}, [urlOrReq, successEventOrEventVector, failureEventOrEventVector]) => { let isVector = { success: true, failure: true } let successEventName = successEventOrEventVector let failureEventName = failureEventOrEventVector if (typeof successEventOrEventVector === 'string') { isVector.success = false } else { successEventName = successEventOrEventVector[0] } if (typeof failureEventOrEventVector === 'string') { isVector.failure = false } else { failureEventName = failureEventOrEventVector[0] } let awesomeness = urlOrReq if (typeof urlOrReq !== 'string') { awesomeness = new Request(urlOrReq.url, R.dissoc('url', urlOrReq)) } (async () => { const res = await fetch(awesomeness) .catch(e => dispatch(failureEventName, isVector.failure ? { res: e, args: failureEventOrEventVector[1] } : e)) const data = R.pick(keys, res) const json = await res.json().catch(e => console.error('error .json()ing', e)) if (res.ok) { dispatch(successEventName, isVector.success ? { res: R.assoc('json', json, data), args: successEventOrEventVector[1] } : R.assoc('json', json, data)) } else { dispatch(failureEventName, isVector.failure ? { res: R.assoc('json', json, data), args: failureEventOrEventVector[1] } : R.assoc('json', json, data),) } })() })
Needs access to dispatch via context (fx api with context 1st arg) or argument to a create fn.
const createFx = ({dispatch}) => fetchFx({dispatch}) // application regFx('fetch', fetchFx.createFx({dispatch}))
https://www.npmjs.com/package/@framework-x/fetch-fx
@framework-x/fetch-fx
pulled from RealWorld exampleNeeds access to dispatch via context (fx api with context 1st arg) or argument to a create fn.