Postingan lainnya
Buku Ini Koding!
Baru!
Buku ini akan jadi teman perjalanan kamu belajar sampai dapat kerjaan di dunia programming!
Kelas Premium!
Belajar Javascript untuk website
Gunakan kupon "mulaijs" untuk diskon 75 ribu!
Cara fetch spesifik data di reactjs
Hallo , mau tanya bagaimana cara untuk fetch spesifik data dari satu user ? contohnya dalam json ada address yang memiliki beberapa bagian seperti Stress, City dll
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
}
yang saya lakukan seperti ini tetapi error TypeError: items.map is not a function
class Wd001comp extends Component{
constructor(props){
super(props)
this.state = {
items:[]
}
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/users/1/")
.then(response => response.json())
.then(data => this.setState({items: data}))
}
render() {
const {items} = this.state
return(
<div>
{items.map((item, index) =>
<p key={index}>Halaman Wd001 {item.address.street}</p>
)}
</div>
);
}
}
1 Jawaban:
Jawaban Terpilih
<div>coba ganti di bagian</div><pre>.then(data => this.setState({items: data}))</pre><div>di "componentDidMount()" menjadi </div><pre>.then(data => this.setState({items: [data]}))</pre><div><br>jadinya sepertin ini:</div><pre> componentDidMount() { fetch("https://jsonplaceholder.typicode.com/users/1/") .then(response => response.json()) .then(data => this.setState({items: [data]})) }</pre><div><br>bisa di check di codesandbox yang saya buat:<a href="https://codesandbox.io/s/competent-hermann-6k3d7?file=/src/Wd001comp.js"><br>https://codesandbox.io/s/competent-hermann-6k3d7?file=/src/Wd001comp.js</a></div>