Skip to content

Instantly share code, notes, and snippets.

@ricklopez
Last active October 30, 2020 19:27
Show Gist options
  • Save ricklopez/4c8a6819c6932f98a4ad115f69af05fe to your computer and use it in GitHub Desktop.
Save ricklopez/4c8a6819c6932f98a4ad115f69af05fe to your computer and use it in GitHub Desktop.

Read (GET)

function getAllContacts(){
  fetch('https://5f217bf8daa42f0016665c89.mockapi.io/api/v1/contacts')
  .then(resp => resp.json())
  .then(renderToys)
}

Create (POST)

function createContact(model){
  fetch('https://5f217bf8daa42f0016665c89.mockapi.io/api/v1/contacts',  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(model)
  })
  .then(resp => resp.json())
  .then(data => doSomethingWithResponse(data))
}

Update (PUT / PATCH)

function updateContact(id, model){
  fetch(`https://5f217bf8daa42f0016665c89.mockapi.io/api/v1/contacts/${id}`,  {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(model)
  })
  .then(resp => resp.json())
  .then(data => doSomethingWithResponse(data))
}

Delete (DELETE)

function deleteContact(id){
  fetch('https://5f217bf8daa42f0016665c89.mockapi.io/api/v1/contacts/${id}`,  {
    method: 'DELETE'
  })
  .then(resp => resp.json())
  .then(data => doSomethingWithResponse(data))
}

More

Form Data

   const options =  {
    method: 'POST', // *GET, POST, PUT, DELETE
    headers:{},
    mode: 'no-cors',
    body: data // body data type must match "Content-Type" header
  };

  delete options.headers['Content-Type'];

fetch(form.action, options)
  .then((res) => {
    console.log(res);
    form.innerHTML = "<h1>Thanks</h1>";
  })
  .catch((e) => {
    //form.innerHTML = "<h1>Thanks</h1>";
    console.log(e)
  })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment