Created
April 9, 2020 18:27
-
-
Save karol-majewski/40099311caa9098ac4c776bb7053afb2 to your computer and use it in GitHub Desktop.
Make PUT and POST requests with fetch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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