Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'cross-fetch' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
} else {
allPairs.unshift(pair);
}
}
function done() {
if (allPairs.length !== 0) {
throw new Error('Not all staged XHRs were executed');
}
}
if (pairs) {
setNextPair(pairs);
}
fetch.mockImplementation(function (url, args) {
var pair = allPairs.shift();
if (!pair) {
throw new Error('We are making a request that we have not anticipated.');
}
if (pair.request.withCredentials !== false) {
// Make sure every request is attaching cookies
expect(args.credentials).toEqual('include');
}
if (pair.request) {
expect(pair.request.uri).toEqual(url);
if (pair.request.headers) {
expect(pair.request.headers).toEqual(args.headers);
}
} else {
allPairs.unshift(pair);
}
}
function done() {
if (allPairs.length !== 0) {
throw new Error('Not all staged XHRs were executed');
}
}
if (pairs) {
setNextPair(pairs);
}
fetch.mockImplementation(function (url, args) {
var pair = allPairs.shift();
if (!pair) {
throw new Error('We are making a request that we have not anticipated.');
}
if (pair.request.withCredentials !== false) {
// Make sure every request is attaching cookies
expect(args.credentials).toEqual('include');
}
if (pair.request) {
expect(pair.request.uri).toEqual(url);
if (pair.request.headers) {
expect(pair.request.headers).toEqual(args.headers);
}
branch: branch,
path,
withAccessToken: !!accessToken,
});
if (repo.private === true) {
const params = { owner: repo.owner.login, repo: repo.name, path: path };
// https://octokit.github.io/rest.js/#api-Repos-getContent
return fetchWithOctokit('repos.getContents', params, accessToken).then(
getContent,
);
}
const relativeUrl = `/${repo.owner.login}/${repo.name}/${branch}/${path}`;
logger.verbose(`Fetching file from public repo ${relativeUrl}`);
return fetch(`${baseRawUrl}${relativeUrl}`).then(response => {
if (response.status === 200) {
return response.text();
}
throw new Error(`Can't fetch ${path} from ${relativeUrl}.`);
});
}
if (!text) {
return reject({
error: 'React-Native-Link-Preview did not receive either a url or text'
});
}
var detectedUrl = null;
text.replace(/\n/g, ' ').split(' ').forEach(function (token) {
if (CONSTANTS.REGEX_VALID_URL.test(token) && !detectedUrl) {
detectedUrl = token;
}
});
if (detectedUrl) {
fetch(detectedUrl)
.then(function (response) {
// get final URL (after any redirects)
const finalUrl = response.url;
// get content type of response
var contentType = response.headers.get('content-type');
if (!contentType) {
return reject({ error: 'React-Native-Link-Preview: Could not extract content type for URL.' });
}
if (contentType instanceof Array) {
contentType = contentType[0];
}
// parse response depending on content type
async function getPage(url, opts) {
const res = await cross_fetch_1.default(url, {
headers: {
Accept: "text/html, application/xhtml+xml",
"User-Agent": opts.userAgent
}
});
const buf = Buffer.from(await res.arrayBuffer());
const contentType = res.headers.get("Content-Type");
const contentLength = res.headers.get("Content-Length");
if (/text\/html|application\/xhtml+xml/.test(contentType) === false) {
throw new unexpectedError_1.default(Object.assign(Object.assign({}, unexpectedError_1.default.EXPECTED_HTML), { info: { contentType, contentLength } }));
}
// no charset in content type, peek at response body for at most 1024 bytes
let str = buf.slice(0, 1024).toString();
let rg;
if (contentType) {
rg = /charset=([^;]*)/i.exec(contentType);
static isOnline( callback ) {
// temporary until we have a ping API
fetch( "/pages/about", {
method: "head",
mode: "no-cors",
cache: "no-store" } ).
then( ( ) => callback( true ) ).
catch( ( ) => callback( false ) );
}
async function fetchGasPrice() {
const res = await fetch(GAS_STATION_URL)
if (res.status !== 200) {
throw new Error(`Fetch returned code ${res.status}`)
}
const jason = await res.json()
if (typeof jason[GAS_PRICE_KEY] !== 'undefined') {
// values come from EGS as tenths of gwei
return jason[GAS_PRICE_KEY] * 1e8
}
throw new Error(`Gas key of ${GAS_PRICE_KEY} is unavailable`)
}
if (init) {
Object.assign(trueInit, defaultInit, init);
} else {
Object.assign(trueInit, defaultInit);
}
trueInit.headers = mergeHeaders([
defaultInit.headers,
// @ts-ignore cross-fetch definitions are broken. See https://github.com/lquixada/cross-fetch/pull/19
input instanceof crossFetch.Request ? input.headers : null,
init && init.headers ? init.headers : null
]);
// @ts-ignore cross-fetch definitions are broken. See https://github.com/lquixada/cross-fetch/pull/19
return new crossFetch.Request(input, trueInit);
}
// in newInit.
if (init) {
for(var key in init) {
if (key==='headers') {
// special case.
continue;
}
newInit[key] = init[key];
}
newInit.headers = mergeHeaders([
newInit.headers,
init.headers
]);
}
var request = new fetch.Request(uri, newInit);
return this.client.fetch(request);
},
if (input === undefined) {
// Nothing was provided, we're operating on the resource uri.
uri = this.uri;
} else if (typeof input === 'string') {
// If it's a string, it might be relative uri so we're resolving it
// first.
uri = url.resolve(this.uri, input);
} else if (input instanceof fetch.Request) {
// We were passed a request object. We need to extract all its
// information into the init object.
uri = url.resolve(this.uri, input.url);
newInit.method = input.method;
newInit.headers = new fetch.Headers(input.headers);
newInit.body = input.body;
newInit.mode = input.mode;
newInit.credentials = input.credentials;
newInit.cache = input.cache;
newInit.redirect = input.redirect;
newInit.referrer = input.referrer;
newInit.integrity = input.integrity;
} else if (input instanceof Object) {
// if it was a regular 'object', but not a Request, we're assuming the
// method was called with the init object as it's first parameter. This
// is not allowed in the default Fetch API, but we do allow it because
// in the resource, specifying the uri is optional.
uri = this.uri;
newInit = input;
} else {