Fetch adalah sebuah teknik untuk melakukan request dan response jaringan. Fetch mengembalikan sebuah Promise sehingga request fetch akan selalu berjalan asynchronous.
Contoh penggunaan fetch
di bawah ini:
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Contoh Penggunaan Fetch untuk Mendapatkan Data:
var base_url = "http://api.football-data.org/v2/";
fetch(base_url + "competitions/2021/standings",{
headers: {
'X-Auth-Token': '***************'
}
})
.then(response => {
return response.json();
})
.then(function(data) {
console.log(data)
}.catch(error => {
console.log(error);
});
Selain itu jika memerlukan pengambilan data secara berulang ditempat lain maka fetch bisa dijadikan sebuah Function Expressions dengan menerapkan headers didalamnya. Seperti berikut :
var base_url = "http://api.football-data.org/v2/";
const fetchApi = function(url) {
return fetch(url, {
headers: {
'X-Auth-Token': '************'
}
});
};
fetchApi(base_url + "competitions/2021/standings")
.then(response => {
return response.json();
})
.then(function(data) {
console.log(data)
}.catch(error => {
console.log(error);
});
Contoh Fetch dengan response success atau failed:
fetch(url)
.then(function(response){
return response.json();
}).then(function (data) {
if (data.status == 'true') {
alert_success(data.message)
else {
alert_failed(data.message)
}
}).catch((err)=>console.log(err))
Contoh Fetch mengambil nilai form dalam field search untuk pencarian data di Laravel:
let form = document.getElementById('pegawai');
form.addEventListener('submit', e => {
e.preventDefault();
const formdata = new FormData(form);
let search = formdata.get('search');
let value = "{{ route('public.search', ":search") }}"
let url = value.replace(':search', search)
fetch(url)
.then(response => response.json())
.then(data => console.log(JSON.stringify(data))
).catch((err)=>console.log(err))
});
Contoh Penggunaan Fetch untuk Mengirim Data :
Untuk mengirim data menggunakan fetch kita perlu menerapkan options dengan properti method POST di dalamnya.
fetch("https://web-server-book-dicoding.appspot.com/add", {
method: "POST"
})
Contoh Mengirim data dengan formdata :
let form = document.getElementById('polling');
form.addEventListener('submit', e => {
e.preventDefault();
let url = "{{ route('polling.store') }}"
fetch(`${url}`, {
method: 'POST',
body : new FormData(form)
}).then(function(response){
}).then(function (data) {
console.log(data);
}).catch((err)=>console.log(err))
})
Contoh lain penggunaan post dari click element.
document.addEventListener('click', (event) => {
let element = event.target;
if(element.matches("#down")) {
const input = {down : element.value};
const link = `{{ route('admin.menuuser.updateuser') }}`;
console.log(input);
fetch(`${link}`,{
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').attr('value')
},
method: 'POST',
body : input
}).then(function(response){
return response.json();
}).then(function (data) {
console.log(data);
}).catch((err)=>console.log(err))
}
});
Penggunaan Post untuk mengirim data JSON :
const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
Aku rasa itu saja beberapa contoh penggunaan fetch yang bisa aku sampaikan, walau sepertinya masih banyak contoh dan bentuk-bentuk penggunaan fetch lain. Kamu bisa lihat selengkapnya di https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch aatau di https://javascript.info/fetch
Tinggalkan Balasan