SO I am calling 5 APIs in my js file and the code is the same for all except the URL and the form data I am passing. and same lines of code repeats 5 times and I think this is not the good of writing. What I want is to make this code dry but don't know what changes I should make
var formdata = new FormData();
formdata.append("market", "KSE100");
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
fetch(
"api_url here_1",
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs',stockData ))
.catch((error) => console.log("error", error));
var formdata = new FormData();
formdata.append("symbol", "SYS");
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
fetch(
"api_url here_2",
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs',stockData ))
.catch((error) => console.log("error", error));
CodePudding user response:
Wrap the common code in a function passing in the form data and url via variables
const sendFormData = (url, formData) => {
var requestOptions = {
method: "POST",
body: formData,
redirect: "follow",
};
fetch(
url,
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs', stockData))
.catch((error) => console.log("error", error));
}
var formdata1 = new FormData();
formdata.append("market", "KSE100");
sendFormData("api_url here_1", formdata1);
var formdata2 = new FormData();
formdata.append("symbol", "SYS");
sendFormData("api_url here_2", formdata2);
CodePudding user response:
You can define a function like this
const postData = (url, data) => {
const formdata = new FormData();
Object.entries(data).forEach(([k, v]) => {
formdata.append(k, v);
}
var requestOptions = {
method: "POST",
body: formdata,
redirect: "follow",
};
return fetch(
url,
requestOptions
)
.then((response) => response.json())
.then((stockData) => console.log('aasfs',stockData ))
.catch((error) => console.log("error", error));
}