Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'isomorphic-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.
it("displays an internal error message", done => {
fetch.mockImplementation(() => Promise.resolve({ status: 500 }))
const login = TestUtils.renderIntoDocument() as Login
TestUtils.Simulate.submit(TestUtils.findRenderedDOMComponentWithTag(login, "form"))
// Wait till the next event loop tick to assert on the expected DOM state,
// because `setState` isn’t going to re-render until the next tick either.
setImmediate(() => {
const error = TestUtils.findRenderedDOMComponentWithClass(login, "error")
expect(error.textContent).toBe("Internal Error. Please contact support@artsy.net")
done()
})
})
getRouteData(route, language) {
const routePath = route === "/" ? "" : route;
const getRoute = fetch(`/data/routes${routePath}/${language}.json`, {
credentials: "include"
})
.then(checkStatus)
.then(response => response.json())
.then(json => convertRouteToLayoutServiceFormat(json));
const context = this.getContext(route, language);
return Promise.all([getRoute, context]).then(results => {
if (results[0].context && results[0].route) {
// contains context and route
return {
sitecore: { ...results[0] }
};
}
return {
sitecore: {
import fetch_ from 'isomorphic-fetch';
import {merge} from 'lodash';
// Fix "Illegal invocation" error in Chrome
// https://github.com/matthew-andrews/isomorphic-fetch/pull/20
const fetch = fetch_.bind(this);
const GITHUB_BASE = 'https://api.github.com/';
function setupRequestOptions(options){
options = merge({
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}, options);
if (typeof options.body === 'object'){
options.body = JSON.stringify(options.body);
}
constructor() {
this.fetch = fetch_.bind(undefined); // this solves an invocation error problem in chrome, according to https://github.com/matthew-andrews/isomorphic-fetch/pull/20
}
import fetch_ from 'isomorphic-fetch';
import {merge} from 'lodash';
// Fix "Illegal invocation" error in Chrome
// https://github.com/matthew-andrews/isomorphic-fetch/pull/20
const fetch = fetch_.bind(this);
const GITHUB_BASE = 'https://api.github.com/';
function setupRequestOptions(options){
options = merge({
method: 'get',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
}, options);
if (typeof options.body === 'object'){
options.body = JSON.stringify(options.body);
}
/* eslint-disable no-bitwise */
const fetch = require('isomorphic-fetch');
const { uniq, map, flatMap } = require('lodash');
const { eosd } = require('../../config/vars');
const { formatISO } = require('../utils/helpers');
fetch.Promise = require('bluebird');
const defaults = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
};
// Grab the correct, sorted sceope from the list of messages
// intended for a transaction
const getScope = messages =>
uniq(
flatMap(messages, msg => [msg.code, ...map(msg.authorization, auth => auth.account)]),
).sort();
const request = async (path, options = {}) => {
export function CustomFetch() {
// pace.start()
const _promise = fetch.apply(this, arguments);
_promise.then(function() {
// pace.stop()
}, function() {
// pace.stop()
});
return _promise;
};
test('Test fetch function on 404 response', () => {
const name = 'test-rest-api';
const endpoint = 'books';
const items = [];
const params = {context: 'view'};
const statusText = 'not-found';
const mockData = {
status: 404,
statusText: statusText,
data: items,
total: items.length,
totalPages: 1
};
require('isomorphic-fetch').__setMockData(mockData);
let called = 0;
const dispatch = action => {
if (called++) {
expect(require('isomorphic-fetch').__getRequestedUrl(mockData)).toBe(`http://wordpress.test/wp-json/wp/v2/${endpoint}?context=view`);
expect(action.type).toBe(`@@wp/${name}/fetched/${endpoint}`);
expect(action.total).toBeUndefined();
expect(action.totalPages).toBeUndefined();
expect(action.results).toBeUndefined();
expect(action.ok).toBeFalsy();
expect(action.message).toBe(statusText);
} else {
expect(action.type).toBe(`@@wp/${name}/fetching/${endpoint}`);
}
test('Test fetchEndpointById function on reject response', () => {
const name = 'test-rest-api';
const endpoint = 'books';
const endpoint2 = 'chapters';
const params = {context: 'view'};
const statusText = '404 not found';
const id = faker.random.number();
const mockData = {
reject: true,
statusText: statusText
};
require('isomorphic-fetch').__setMockData(mockData);
let called = 0;
const dispatch = action => {
if (called++) {
expect(require('isomorphic-fetch').__getRequestedUrl(mockData)).toBe(`http://wordpress.test/wp-json/wp/v2/${endpoint}/${id}/${endpoint2}?context=view`);
expect(action.type).toBe(`@@wp/${name}/fetched-by-id/${endpoint}/${endpoint2}`);
expect(action.result).toBeUndefined();
expect(action.ok).toBeFalsy();
expect(action.message).toBe(statusText);
} else {
expect(action.type).toBe(`@@wp/${name}/fetching-by-id/${endpoint}/${endpoint2}`);
}
expect(action.params).toEqual(params);
expect(action.id).toBe(id);
test('Test fetch function on reject response', () => {
const name = 'test-rest-api';
const endpoint = 'books';
const endpoint2 = 'chapters';
const params = {context: 'view'};
const statusText = '404 not found';
const mockData = {
reject: true,
statusText: statusText
};
require('isomorphic-fetch').__setMockData(mockData);
let called = 0;
const dispatch = action => {
if (called++) {
expect(require('isomorphic-fetch').__getRequestedUrl(mockData)).toBe(`http://wordpress.test/wp-json/wp/v2/${endpoint}/${endpoint2}?context=view`);
expect(action.type).toBe(`@@wp/${name}/fetched/${endpoint}/${endpoint2}`);
expect(action.total).toBeUndefined();
expect(action.totalPages).toBeUndefined();
expect(action.results).toBeUndefined();
expect(action.ok).toBeFalsy();
expect(action.message).toBe(statusText);
} else {
expect(action.type).toBe(`@@wp/${name}/fetching/${endpoint}/${endpoint2}`);
}