Friday, February 2, 2024

Global Api Call (Create Props Function )

 Global Api Call

(Create Props Function )


1 // import  public Folder > index.html

   <title>React App</title>

  <script src="%PUBLIC_URL%/apigetdata.js"></script>

2 // in public folder create this file : -     apigetdata.js


//GET Api call Props function

async function apiGetData(url) {
  const swapiUrl = url;
  let res = await fetch(swapiUrl);
  // let resJson = await res.json();
  if (res.ok) {
    let resJson = await res.json();
    return resJson;
  }
  else {
    throw new Error('Network res was not ok.');
  }

  // return resJson;
}


//POST Api call Props function

async function postData(url = "", data = {}) {

  const response = await fetch(url, {

    method: "POST", // *GET, POST, PUT, DELETE, etc.
    mode: "cors", // no-cors, *cors, same-origin

    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data), // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

// postData("http://surevih.in/api/posthello", { answer: 42 }).then((data) => {
//   console.log(data); // JSON data parsed by `data.json()` call
// });

No comments:

Post a Comment