AJAX

Libraries

Using the native XMLHttpRequest API is not easy, especially if you need to fetch across domains. For this reason, most people reach for an library that abstracts some of the complexity away. You could use the newer Fetch API, but that is not supported on IE and you’d still want to abstract away some of the complexity. My recommendation:

Fetch API

Using Fetch from CSS-Tricks does a great job of explaining how to use Fetch in a production environment.

I have had great success when fetching like this:

export function fetchData (userId) {
	const httpRequest = {
		method: 'GET',
		credentials: 'include',
		headers: { Accept: 'application/json' }
	};

	return fetch(`/api/customer/${userId}`, httpRequest)
		.then(response => {
			if (!response.ok) {
				throw new Error('The response was not OK.');
			}
			return response.json(); // This is a Promise.
		})
		.catch(error => {
			// Note: “error” will e a TypeError.
			// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
			console.log( // eslint-disable-line
				`Could not fetch /api/customer/${userId} because ${error.message}`
			);
			return ''; // Hide error by resolving (successfully)
			// Alternatively, you could remove this .catch() entirely or do:
			// return Promise.reject('Custom error message')
			// if you want to return a rejected Promise.
		});
}

XMLHttpRequest