api-fetcher-treeline
Install
npm install --save api-fetcher-treeline
To polyfill Promise
and fetch
see here
Basic usage
// In api.js ...; const setupApiFetcher = { const api = urlPrefix; if processenvNODE_ENV === 'production' api; return api;}; const api = ; ;
Then use it in react components:
import React from 'react';import api from '../api'; Component state = todos: ; { return <div ="some-content" />; } // Send a GET request to endpoint /todos wrapped // in the ability to cancel it if the component unmounts // before the fetch has completed { thisfetchRequest = api; const promise = thisfetchRequest; promise } // Always cancel your requests in componentWillUnmount. This will have no effect // if the Promise has already resolved and its side effects have been issued. { thisfetchRequest; // or `api.revoke(this.fetchRequest);` }
Here is the class definition with some comments.
;; { thisapi = urlPrefix config; } // Use this to alter the default options passed to the fetch api { thisapi; } // Sends a plain GET request using the Fetch api { return thisapi; } // Sends a 'WrappedPromise' GET request (see notes below...) { return ; } { return thisapi; } // 'body' is the request body passed to fetch. It will be Json.stringify()ed { return ; } { return thisapi; } { return ; } { return thisapi; } { return ; } {...} // cancels a cancelableRequest
All the "cancelable" methods return a "WrappedPromise" object that is shaped like this:
const wrappedPromiseExample = promise: Promise // This key points to the actual pending Promise cancel: Function // This function will reject() the Promise;
Here are the default options passed on to the browser fetch api
const defaultFetchOptions = headers: 'Access-Control-Allow-Origin': '*' 'Content-Type': 'application/json ; charset=utf-8' credentials: 'include' mode: 'cors';
To overwrite these options, use the setFetchOptions()
method
const setupApiFetcher = { const api = urlPrefix; if processenvNODE_ENV === 'production' api; return api;};
If for some reason you neeed to hook into the response
object, use config.onResponse()
const config = { if responsestatus !== 401 return response; else throw 'Response is not ok'; }; const api = 'http://hello.com/api' config;api;
Contributing
To run the test suite, run npm test
.
License
MIT.