Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make my code dry in JavaScript during API Call

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));

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading