3 Cara Fetch Data di ReactJs

gambar ini dibuat menggunakan Canva.com
$ # example command for start new project ReactJS
$ create-react-app 3waytofetch
Creating a new React app in /home/user/3waytofetch.
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts...
$ cd 3waytofetch 
$ cat package.json
{
"name": "3waytofetch",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-scripts": "1.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
}
}
normal & mostly use
state = {
data : []
}
componentDidMount(){
const urlFetch = fetch('alamaturl')
urlFetch.then( res => {
if(res.status === 200)
return res.json()
}).then( resJson => {
this.setState({
data: resJson
})
})
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise#Description
const FungsiAsync = async () => {
const urlFetch = await fetch('url'} # fetch is Promise object
# fetch kembaliannya dalam bentuk promise , maka
# baris code setelah await fetch akan di kerjakan sampai promise
# atau fungsi fetch tersebut selesai.
# jika telah selesai , maka lanjut pada statement return dibawah
# ini.
# return jika 'json' in urlFetch benar maka
# return await urlFetch.json() , jika false maka
# return Array []
return 'json' in urlFetch ? await urlFetch.json() : []
# mengapa await urlFetch.json() ?
# urlFetch.json masih bernilai Object Promise , dengan
# menambahkan await maka kita akan resolve dan
# mendapatkan nilai JSON
}
kehidupan yang terjadi di Cara ke-2.
const AsyncFetch = async (url) => {
const urlFetch = await fetch(url)
return urlFetch.status === 200 && 'json' in urlFetch ?
await urlFetch.json() : []
}
export default AsyncFetch
...
import AsyncFetch from './AsyncFetch'
...
async componentDidMount(){
const url = "your url"
this.setStateAsync({
data: await AsyncFetch(url)
})
}

--

--

TinkeREr & Opensource it’s my DNA

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store