Universitas Kebudayaan Digital Makassar

Universitas Kebudayaan Digital Makassar (UKDMKS) memadukan inovasi teknologi digital dengan pelestarian budaya lokal. Bergabunglah untuk membangun masa depan berbasis budaya dan teknologi!

javascript

Belajar Menggunakan Fetch di Javascript

Solution: Menerapkan Fetch pada Proyek Club Finder

Apakah Anda sudah berhasil menerapkan Fetch dalam menampilkan data dari API TheSportDB? Jika belum, yuk kita lakukan bersama-sama!
Pada dokumentasi API menyebutkan bahwa, untuk mendapatkan daftar klub olahraga kita dapat menggunakan target url: https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=Arsenal
2020031323502200000abb4fd3bf7637506d2872ff1cb0.png
Sebelum menuliskan langsung pada proyek dengan fetch, biasakan ketika hendak mengkonsumsi API biasakan untuk mencobanya menggunakan aplikasi Postman terlebih dahulu. 
Jika target url tersebut diakses melalui Postman dengan GET Request, maka akan menghasilkan response dengan struktur JSON yang tampak pada tab Body.
202003132350321a588cd4b3f0285be6fd1af52fa3591e.png
Pada response JSON yang dihasilkan menampung satu key dengan nama teams yang memiliki value berupa sebuah array. 
Di dalam array tersebut menampilkan banyak data terkait klub olahraga yang memiliki nama Arsenal. 
Kita dapat memanfaatkan key strTeam untuk mendapatkan nama klub, strTeamBadge untuk mendapatkan logo klub, dan strDescriptionEN untuk mendapatkan deskripsi singkat dalam bahasa inggris.
Lantas untuk mencari data team berdasarkan kata kunci lain kita dapat mengubah kata “Arsenal” menggunakan kata kunci yang kita inginkan, misalnya “Barcelona”
Sehingga melakukan request terhadap url: https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=Barcelona akan menghasilkan response JSON dengan informasi klub olahraga terkait “Barcelona”.
20200313235048e7906db6f58df01a750d175c26f3b342.png
Cukup mudah bukan untuk menggunakan API tersebut?
Nah, Setelah memahami cara penggunaan API-nya, sekarang mari kita mulai tuliskan fungsi fetch pada proyek Club Finder. Langkah awal buka kembali proyek Club Finder pada text editor yang Anda gunakan.
202003132351017c49f82cb83c52af812adb0b076cc23f.png
Kemudian buka berkas data-source.js pada src -> script -> data -> data-source.js. Kita refactor fungsi searchClub dengan menghapus seluruh logika yang ada di dalamnya, kemudian tuliskan fungsi fetch seperti ini:
  1. class DataSource {
  2.    static searchClub(keyword) {
  3.        return fetch(`https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${keyword}`)
  4.    }
  5. }
  6.  
  7. export default DataSource;

Seperti yang sudah kita ketahui, fungsi fetch() akan mengembalikan promise resolve jika request berhasil dilakukan. Maka untuk menangani respon dari request yang dibuat, kita gunakan .then() yang di dalamnya berisi variabel response sebagai response object yang didapat.

  1. class DataSource {
  2.    static searchClub(keyword) {
  3.        return fetch(`https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${keyword}`)
  4.        .then(response => {
  5.           
  6.        })
  7.    }
  8. }
  9.  
  10. export default DataSource;

Kemudian di dalam blok then tersebut, kita ubah nilai response menjadi JSON dengan memanggil method response.json().

  1. class DataSource {
  2.    static searchClub(keyword) {
  3.        return fetch(`https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${keyword}`)
  4.        .then(response => {
  5.            return response.json();
  6.        })
  7.    }
  8. }
  9.  
  10. export default DataSource;

Karena method response.json() juga mengembalikan nilai promise, maka untuk mendapatkan nilai yang dibawa oleh resolve kita perlu menambahkan .then lainnya (chaining promise). 

Di dalam .then yang kedua ini, berikan parameter dengan nama responseJson (penamaan variabel tidaklah baku, namun gunakan penamaan yang menunjukkan arti dari nilai variabelnya).


  1. class DataSource {
  2.    static searchClub(keyword) {
  3.        return fetch(`https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${keyword}`)
  4.        .then(response => {
  5.            return response.json();
  6.        })
  7.        .then(responseJson => {
  8.           
  9.        })
  10.    }
  11. }
  12.  
  13. export default DataSource;

responseJson merupakan nilai JSON yang dihasilkan dari perubahan object response dalam bentuk JSON melalui method .json() tadi.
Di dalam block .then yang kedua, kita kembalikan (return) dengan nilai promise resolve dengan membawa nilai jsonResponse.teams jika nilai array tidak null
Namun jika teams bernilai null, maka kembalikan dengan nilai promise reject dengan membawa nilai “${keyword} is not found”.
  1. class DataSource {
  2.    static searchClub(keyword) {
  3.        return fetch(`https://www.thesportsdb.com/api/v1/json/1/searchteams.php?t=${keyword}`)
  4.        .then(response => {
  5.            return response.json();
  6.        })
  7.        .then(responseJson => {
  8.            if(responseJson.teams) {
  9.                return Promise.resolve(responseJson.teams);
  10.            } else {
  11.                return Promise.reject(`${keyword} is not found`);
  12.            }
  13.        })
  14.    }
  15. }
  16.  
  17. export default DataSource;
Simpan perubahan tersebut dan jalankan aplikasi dalam mode development menggunakan perintah:


  1. npm run start-dev


Setelah proyek terbuka, lakukan pencarian dengan keyword apapun yang Anda mau, di sini kita contohkan dengan “Barcelona”.

20200313235133e90126ea84a6df29dc44b91c4f296331.png
Yah, data yang ditampilkan undefined. Mengapa bisa demikian? Ini disebabkan karena kita belum menyesuaikan key berdasarkan response yang didapat dari public API. Kita harus menggunakan key strTeam untuk mendapatkan nama klub, strTeamBadge untuk mendapatkan logo klub, dan strDescriptionEN untuk mendapatkan deskripsi singkat dalam bahasa inggris.
Ketiga key tersebut kita tetapkan pada berkas src -> script -> component -> club-item.js. Lebih tepatnya pada fungsi render.
  1. render() {
  2.        this.shadowDOM.innerHTML = `
  3.            <style>
  4.                 ……..
  5.            </style>
  6.            <img class=”fan-art-club” src=”${this._club.fanArt}” alt=”Fan Art”>
  7.            <div class=”club-info”>
  8.                <h2>${this._club.name}</h2>
  9.                <p>${this._club.description}</p>
  10.            </div>`;
  11.    }

Kita ubah properti this._club.fanArt menjadi this._club.strTeamBadgethis._club.name menjadi this._club.strTeam, dan this._club.description menjadi this._club.strDescriptionEN.
Sehingga fungsi render akan menjadi seperti ini:
  1. render() {
  2.        this.shadowDOM.innerHTML = `
  3.            <style>
  4.                * {
  5.                    margin: 0;
  6.                    padding: 0;
  7.                    box-sizing: border-box;
  8.                }
  9.                :host {
  10.                    display: block;
  11.                    margin-bottom: 18px;
  12.                    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  13.                    border-radius: 10px;
  14.                    overflow: hidden;
  15.                }
  16.               
  17.                .fan-art-club {
  18.                    width: 100%;
  19.                    max-height: 300px;
  20.                    object-fit: cover;
  21.                    object-position: center;
  22.                }
  23.               
  24.                .club-info {
  25.                    padding: 24px;
  26.                }
  27.               
  28.                .club-info > h2 {
  29.                    font-weight: lighter;
  30.                }
  31.               
  32.                .club-info > p {
  33.                    margin-top: 10px;
  34.                    overflow: hidden;
  35.                    text-overflow: ellipsis;
  36.                    display: -webkit-box;
  37.                    -webkit-box-orient: vertical;
  38.                    -webkit-line-clamp: 10; /* number of lines to show */
  39.                }
  40.            </style>
  41.            <img class=”fan-art-club” src=”${this._club.strTeamBadge}” alt=”Fan Art”>
  42.            <div class=”club-info”>
  43.                <h2>${this._club.strTeam}</h2>
  44.                <p>${this._club.strDescriptionEN}</p>
  45.            </div>`;
  46. }

Simpan kembali perubahan kode yang dituliskan kemudian lakukan pencarian kembali pada aplikasi Club Finder. Seharusnya sekarang aplikasi sudah bisa menampilkan data dengan baik.


202003132351502bc06712f0552fa6f26e8f8de5607033.png
Voila! Anda sudah berhasil menerapkan Fetch pada proyek Club Finder.
Langkah dari solution ini bisa Anda temukan juga pada repository berikut: https://github.com/dicodingacademy/a163-bfwd-labs/tree/112-club-finder-fetch-solution
Asalas | Unlock Anime, Manhwa & Donghua Like Never BeforeFinasteriden: Unlock the Secrets of the Movie World!Marians Woman: Celebrating Beauty Around the WorldArheon - Unveiling the Secrets of Food & Origins WorldwideMPAPER The Ultimate Destination for Anime & Manga FansANMC21: Your Guide to Smarter Living and SuccessMV Agusta of Tampa: Your Automotive News HubTech and Play: Your Hub for Technology, Gaming, and GadgetsRebeccaSommer : Stories & Cultures from Around the WorldUETRABAJANDOJUNTOS - Inside the Music World’s Best-Kept SecretsVandelay Armor - Viral News and Global UpdatesGainesville Sun: Technology & Computers UnveiledGRFX Gaming Party Bus: Journey Through Gaming ErasHouse of Beauty: Celebrating the World's Most Beautiful WomenLearn Mistake: Wisdom for a Better LifeSports Hope Alive: Portal Olahraga DuniaWorld News TW - The Hottest Viral News & Global HeadlinesWriter Sujatha - Life Lessons & Struggles That Inspirehttps://128.199.185.186/https://143.198.89.74/https://165.227.47.178/https://170.64.208.214/https://170.64.192.239/https://46.101.102.216/LVONLINEtelegram lvonlinehttps://www.thecarbongenie.com/https://www.aievea-bijou.com/https://www.slashpolicy.com/https://www.benwestbeech.com/https://www.hh-bags.com/https://www.drupalforfacebook.org/https://www.lvonline.boats/https://www.lvoslot.com/https://www.lvobet.id/https://www.lvoslot.id/https://www.lvonline000.com/https://www.lvonline001.com/https://www.lvonline002.com/https://www.lvonline003.com/https://www.lvonline004.com/https://www.lvonline005.com/https://www.lvonline006.com/https://www.lvonline007.com/https://www.lvonline008.com/https://www.lvonline009.com/https://www.lvonline010.com/https://www.lvonlinepoker.com/https://www.lvonlinebola.com/https://www.lvonlinekasino.com/https://www.lvonline.io/https://www.lvonline.store/https://www.lvonline.online/https://www.situslvonline.us/situs bandar lvonlinehttps://146.190.97.83/https://143.198.209.134/https://188.166.246.204/https://167.172.83.179/https://togelhok.tv/https://www.togelhok.id/https://earthtoweb.com/https://www.elearningfacultymodules.org/https://www.how6youtoknowc.org/https://128.199.71.129/https://167.172.64.185/https://152.42.192.250/https://www.capcut88.com/https://www.capcut88.co/https://towsonsmiles.com/https://www.campur88.com/https://www.campur88.org/https://www.campur88.work/https://www.campur88.xyz/https://www.campur88.lol/https://www.nagacampur.biz/https://www.nagacampur.club/https://www.nagacampur.co/https://www.nagacampur.me/https://www.nagacampur.xyz/https://www.nasicampur88.com/https://165.232.175.185/https://152.42.164.228/https://152.42.194.203/https://152.42.169.214/https://www.campurslot.com/https://www.campurslot.id/https://www.campurslot.co/https://www.campurslot.org/https://www.campurslot.homes/https://www.campurslot.design/Badan Lembaga Pendidikan Ilmu Komputer SubangUniversitas Negeri JeparaLembaga Universitas Kristen MaranthaSMP 3 Negri Nganjukhttps://iklanmalay.com/https://promobola.comhttps://kapsychologists.comhttps://propertycloudsite.comSattar777 NewsVR Slot Online NewsRuby888 Online Slot NewsBerita Global Klik Agenslot228Agen Sloto SG777 NewsGold Club SlotOnline NewsAzar Marra Kech NewsBerita Sidney dan MancanegaraBerita Seputar Sumsel dan DuniaBerita Rehabilitasi Judi OnlineBerita Link Gacor TerupdateItalian Tuition News UpdateWPJS Online NewsBerita Agen Slot RoyalThai Slot Online NewsAll Online Game NewsOnline Game News UpdateAsian Lotre NewsBerita Demo Dana SlotBerita Kalbar ProvLocanda della Maria NewsWye Valley NewsBerita Agen Slot1004Berita Agen Slot33Agen Slot399 NewsPlayboy Slot Online NewsSlot Online BB Slot NewsSlot Online 911 News365 Slot Online NewsEat Atlah Newsambamali canadaInfo Seputar Sepakbolacentre thoughtBerita Hiburanopen etherpadras indo groupresistance manualPrediksi Shiowe want real newsthe poisoned pawnindonesia reclaimed teakswift kennedy and copullip passionmy passion foraim torontoPublic FlashesFriweb TeknologiIngenious Gamersthe late show gardensGishPuppy Newsslot danaOregon Farm Garden NewsViral Pulse GlobaljumpajpPromo Bola soccer Captivates The WorldKapsychologists World First The Science of Mental Health - Understanding Psychiatry: The Science of Mental HealthPropertyCloudSite How to Make Smarter Investments in Today’s MarketArnavichara Ultimate Guide Right Business SoftwareAuscare Disability A Comprehensive Guide to Retirement Homes Finding the Perfect Place to Enjoy Your Golden YearsSeries Mp4 The Future of Entertainment Streaming and Downloadable Video ExplainedAlogirlxinh How to Create a Successful Personal Page or Blog in 2024ihokibethttps://bengbulang-karangpucung.cilacapkab.go.id/https://comunicacion.unsa.edu.ar/https://seychellesbiodiversitychm.sc/https://www.925lms.com/https://www.guisseny.memoire.bzh/https://www.mobiliars.org/https://www.squashparkwieliczka.pl/
Asalas | Unlock Anime, Manhwa & Donghua Like Never BeforeFinasteriden: Unlock the Secrets of the Movie World!Marians Woman: Celebrating Beauty Around the WorldArheon - Unveiling the Secrets of Food & Origins WorldwideMPAPER The Ultimate Destination for Anime & Manga FansANMC21: Your Guide to Smarter Living and SuccessMV Agusta of Tampa: Your Automotive News HubTech and Play: Your Hub for Technology, Gaming, and GadgetsRebeccaSommer : Stories & Cultures from Around the WorldUETRABAJANDOJUNTOS - Inside the Music World’s Best-Kept SecretsVandelay Armor - Viral News and Global UpdatesGainesville Sun: Technology & Computers UnveiledGRFX Gaming Party Bus: Journey Through Gaming ErasHouse of Beauty: Celebrating the World's Most Beautiful WomenLearn Mistake: Wisdom for a Better LifeSports Hope Alive: Portal Olahraga DuniaWorld News TW - The Hottest Viral News & Global HeadlinesWriter Sujatha - Life Lessons & Struggles That Inspirehttps://128.199.185.186/https://143.198.89.74/https://165.227.47.178/https://170.64.208.214/https://170.64.192.239/https://46.101.102.216/LVONLINEtelegram lvonlinehttps://www.thecarbongenie.com/https://www.aievea-bijou.com/https://www.slashpolicy.com/https://www.benwestbeech.com/https://www.hh-bags.com/https://www.lvonline.boats/https://www.lvoslot.com/https://www.lvobet.id/https://www.lvoslot.id/https://www.lvonline000.com/https://www.lvonline001.com/https://www.lvonline002.com/https://www.lvonline003.com/https://www.lvonline004.com/https://www.lvonline005.com/https://www.lvonline006.com/https://www.lvonline007.com/https://www.lvonline008.com/https://www.lvonline009.com/https://www.lvonline010.com/https://www.lvonlinepoker.com/https://www.lvonlinebola.com/https://www.lvonlinekasino.com/https://www.lvonline.io/https://www.lvonline.store/https://www.lvonline.online/https://www.situslvonline.us/situs bandar lvonlinehttps://146.190.97.83/https://143.198.209.134/https://188.166.246.204/https://167.172.83.179/https://togelhok.tv/https://www.togelhok.id/https://earthtoweb.com/https://www.elearningfacultymodules.org/https://www.how6youtoknowc.org/https://128.199.71.129/https://167.172.64.185/https://152.42.192.250/https://www.capcut88.com/https://www.capcut88.co/https://towsonsmiles.com/https://www.campur88.com/https://www.campur88.org/https://www.campur88.work/https://www.campur88.xyz/https://www.campur88.lol/https://www.nagacampur.biz/https://www.nagacampur.club/https://www.nagacampur.co/https://www.nagacampur.me/https://www.nagacampur.xyz/https://www.nasicampur88.com/https://165.232.175.185/https://152.42.164.228/https://152.42.194.203/https://152.42.169.214/https://www.campurslot.com/https://www.campurslot.id/https://www.campurslot.co/https://www.campurslot.org/https://www.campurslot.homes/https://www.campurslot.design/Badan Lembaga Pendidikan Ilmu Komputer SubangUniversitas Negeri JeparaLembaga Universitas Kristen MaranthaSMP 3 Negri Nganjukhttps://iklanmalay.com/https://promobola.comhttps://kapsychologists.comhttps://propertycloudsite.comSattar777 NewsVR Slot Online NewsRuby888 Online Slot NewsBerita Global Klik Agenslot228Agen Sloto SG777 NewsGold Club SlotOnline NewsAzar Marra Kech NewsBerita Sidney dan MancanegaraBerita Seputar Sumsel dan DuniaBerita Rehabilitasi Judi OnlineBerita Link Gacor TerupdateItalian Tuition News UpdateWPJS Online NewsBerita Agen Slot RoyalThai Slot Online NewsAll Online Game NewsOnline Game News UpdateAsian Lotre NewsBerita Demo Dana SlotBerita Kalbar ProvLocanda della Maria NewsWye Valley NewsBerita Agen Slot1004Berita Agen Slot33Agen Slot399 NewsPlayboy Slot Online NewsSlot Online BB Slot NewsSlot Online 911 News365 Slot Online NewsEat Atlah Newsambamali canadaInfo Seputar Sepakbolacentre thoughtBerita Hiburanopen etherpadras indo groupresistance manualPrediksi Shiowe want real newsthe poisoned pawnindonesia reclaimed teakswift kennedy and copullip passionmy passion foraim torontoPublic FlashesFriweb TeknologiIngenious Gamersthe late show gardensGishPuppy Newsslot danaOregon Farm Garden NewsViral Pulse GlobaljumpajpPromo Bola soccer Captivates The WorldKapsychologists World First The Science of Mental Health - Understanding Psychiatry: The Science of Mental HealthPropertyCloudSite How to Make Smarter Investments in Today’s MarketArnavichara Ultimate Guide Right Business SoftwareAuscare Disability A Comprehensive Guide to Retirement Homes Finding the Perfect Place to Enjoy Your Golden YearsSeries Mp4 The Future of Entertainment Streaming and Downloadable Video ExplainedAlogirlxinh How to Create a Successful Personal Page or Blog in 2024ihokibethttps://bengbulang-karangpucung.cilacapkab.go.id/https://comunicacion.unsa.edu.ar/https://seychellesbiodiversitychm.sc/https://www.925lms.com/https://www.guisseny.memoire.bzh/https://www.mobiliars.org/https://www.squashparkwieliczka.pl/https://mok.edu.kz/https://www.mware.cloud/https://www.facilitiescoolingandheating.com.au/https://www.krillpay.ng/https://925worksuite.com/