This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
react-rest-request/src/misc.ts
Dmitriy Pleshevskiy 243f4f77e5 feat!(client): add client fetch based
breaking!(context): client prop instead base url
refac: change axios response to client response
chore(deps): remove axios
chore: update example

Closes #2
2020-11-05 00:23:57 +03:00

33 lines
972 B
TypeScript

export function isObject(val: any) {
return Object.prototype.toString.call(val) === '[object Object]';
}
export function formDataFromObject(obj: Record<string, any>) {
const formData = new FormData();
for (const [key, value] of Object.entries(obj)) {
if (Array.isArray(value)) {
value.forEach(val => formData.append(key, val));
} else if (isObject(value)) {
formData.set(key, JSON.stringify(value));
} else {
formData.set(key, value);
}
}
return formData;
}
export function urlSearchParamsFromObject(obj: Record<string, any>) {
const searchParams = new URLSearchParams();
for (const [key, value] of Object.entries(obj)) {
if (Array.isArray(value)) {
const arrayKey = `${key}[]`;
value.forEach(val => searchParams.append(arrayKey, val));
} else {
searchParams.set(key, value);
}
}
return searchParams;
}