How to use unfetch - 10 common examples

To help you get started, we’ve selected a few unfetch examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nav-e / nav-e / src / Nav-e.js View on Github external
getRoutes = (waypoints) => {
    const routes = [];
    let counterRoutes = 0;
    if (waypoints.length > 0) {
      this.showLoader();
    }

    for (let i = 0; i < waypoints.length - 1; i += 1) {
      const startOsmId = waypoints[i];
      const destinationOsmId = waypoints[i + 1];
      const url = `${NaveServerAddress}astar/from/${startOsmId}/to/${destinationOsmId}`;
      fetch(url)
        .then((response) => {
          if (response.status > 400) {
            console.log("Server Error");
            throw new Error('Failed to load route data!');
          }
          else {
            return response.text();
          }
        })
        .then((routeReceived) => {
          // The array received from rt-library is actually from dest to orig,
          // so we gotta reverse for now.
          try {
            routes[i] = routeReceived.reverse();
            counterRoutes += 1;
            // We use counterRoutes instead of "i" because we don't know the order that
github Automattic / jetpack / modules / search / instant-search / lib / api.js View on Github external
const queryString = encode(
		flatten( {
			aggregations,
			fields,
			highlight_fields,
			filter: buildFilterObject( filter ),
			query: encodeURIComponent( query ),
			sort,
			page_handle: pageHandle,
		} )
	);

	const remoteURL = `https://public-api.wordpress.com/rest/v1.3/sites/${ siteId }/search?${ queryString }`;
	const localURL = `/?rest_route=/jetpack/v4/search-local&${ queryString }`;

	return fetch(
		// @todo - send is_dev_mode to JS.
		document.location.origin.includes( '.' ) ? remoteURL : localURL
	).then( response => {
		return response.json();
	} );
	//TODO: handle errors and fallback to a longer term cache - network connectivity for mobile
	//TODO: store cache data in the browser - esp for mobile
}
github babel / website / js / repl / CircleCI.js View on Github external
async function sendRequest(repo: ?string, uri: string): Promise {
  const urlRepo = repo && repo.length ? repo : "babel/babel";
  const fullURL = `https://circleci.com/api/v1.1/project/github/${urlRepo}/${uri}`;
  let response;
  try {
    response = await fetch(fullURL).then(res => res.json());
  } catch (ex) {
    throw new Error(`Error sending request to CircleCI: ${ex.message}`);
  }
  // CircleCI sometimes returns errors as 200 (OK) responses with a "message"
  // field...
  if (response.message) {
    throw new Error(response.message);
  }
  return response;
}
github klembot / twinejs / src / common / app / update-check.js View on Github external
export default function(latestBuildNumber, callback) {
	fetch('https://twinery.org/latestversion/2.json')
		.then(r => r.json())
		.then(data => {
			if (data.buildNumber > latestBuildNumber) {
				callback(data);
			}
		});
}
github cheeaun / earth / assets / app.js View on Github external
function render() {
    if (num >= number) return;
    num = num + inc;
    if (num > number) num = number;
    el.textContent = numberWithCommas(num);
    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);
};

Promise.all([
  new Promise((resolve, reject) => {
    map.once('styledata', resolve);
    map.on('error', reject);
  }),
  fetch(require('../data/checkins.min.geojson')).then((data) => data.json()),
]).then(([_, data]) => {
  const _countries = {};
  const _places = {};

  const checkinsCount = data.features.length;

  const lines = [];

  data.features = data.features.filter((f, i) => {
    const { id, country } = f.properties;
    const isUnique = !_places[id];
    const [lng, lat] = f.geometry.coordinates;
    if (isUnique) {
      if (!_countries[country]) {
        const cc = f.properties.cc.toLowerCase();
        _countries[country] = {
github ritz078 / embed-js / src / js / modules / video / vimeo.js View on Github external
return new Promise((resolve) => {
		fetch(url)
			.then((data) => data.json())
			.then((json) => resolve(json[0]))
	})
}
github jhnns / spa-vs-universal / spa / client / api / posts / getTop5.js View on Github external
export default function getTop5() {
    return fetch(`${ config.root }/posts?limit=5&sortBy=starred`)
        .then(res => res.json())
        .then(res => res.items);
}
github aganglada / chicky / src / index.js View on Github external
const request = (method, url, options = {}) =>
        unfetch(
            url,
            Object.assign({}, options, {
                method
            })
        ).then(handleErrors);
github jhnns / spa-vs-universal / spa / client / api / session / create.js View on Github external
export default function create(payload) {
    return fetch(`${ config.root }/session`, {
        ...defaultOptions,
        body: JSON.stringify(payload),
    })
        .then(res => res.json())
        .then(res => {
            if (res.status === "success") {
                updateLocalSession(res.data);

                return res.data;
            }

            throw new Error(res.message);
        });
}
github xkcd / alto / src / Client.js View on Github external
logEnter(parentId, menuId) {
    fetch(`${this.baseURL}/enter/${this.sessionId}/${parentId}/${menuId}?${Date.now()}`).catch(e => {})
  }

unfetch

Bare minimum fetch polyfill in 500 bytes

MIT
Latest version published 1 year ago

Package Health Score

70 / 100
Full package analysis