Skip to content

Instantly share code, notes, and snippets.

@jeremyadavis
Created November 15, 2018 15:07
Show Gist options
  • Select an option

  • Save jeremyadavis/1188a6a7329e54ba2dc1be9815a54d9a to your computer and use it in GitHub Desktop.

Select an option

Save jeremyadavis/1188a6a7329e54ba2dc1be9815a54d9a to your computer and use it in GitHub Desktop.
// saga.js
export function* processSaveAttachment(action) {
const files = action && action.payload;
const requestData = new FormData();
files.forEach((file) => requestData.append('upfile', file));
// console.log('[files]', files);
// for (const pair of requestData.entries()) {
// console.log(`${pair[0]}, ${pair[1]}`);
// }
try {
const payload = yield call(attachmentsApi.createAttachments, requestData); // Basic POST request
yield put(saveAttachmentsSuccess(payload));
} catch (e) {
yield put(saveAttachmentsFailure(new Error(e)));
}
}
// apiHelper.js
export default function request(url, method, data) {
return setupRequest(url, method, data)
.then((formattedRequest) => fetch(formattedRequest.url, formattedRequest.options))
.then(checkStatus)
.then(parseJSON)
.then(processJSON)
.catch(handleError);
}
function setupRequest(url, method = 'GET', data) {
const requestHasData = method === 'POST' || method === 'PUT';
const options = {
method,
credentials: 'same-origin',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
};
if (requestHasData) {
if (typeof (data) !== 'object') {
return new Error('Unknown data type given');
}
const objectClass = Object.prototype.toString.call(data).slice(8, -1);
if (objectClass !== 'FormData') {
options.body = JSON.stringify(data);
} else {
options.body = data;
options.headers = { Accept: '*/*' };
}
}
return Promise.resolve({
url,
options,
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment