Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Created April 9, 2020 18:27
Show Gist options
  • Save karol-majewski/40099311caa9098ac4c776bb7053afb2 to your computer and use it in GitHub Desktop.
Save karol-majewski/40099311caa9098ac4c776bb7053afb2 to your computer and use it in GitHub Desktop.
Make PUT and POST requests with fetch
type ContentType = 'application/x-www-form-urlencoded' | 'application/json';
/**
* POJO payloads used to make PUT and POST requests made with `fetch`
* need to be converted to a format `fetch` accepts first.
*/
export const serialize = (payload: object, type: ContentType): string => {
switch (type) {
case 'application/x-www-form-urlencoded':
return Object.entries(payload)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
case 'application/json':
return JSON.stringify(payload);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment