import React, {Component} from 'react';
import './randomChar.css';
import GotService from '../../services/gotService';
export default class RandomChar extends Component {
constructor(props){
super(props);
this.state = {
name: '',
gender: '',
born: '',
died: '',
culture: ''
}
}
getData(){
const got = new GotService();
const random = Math.round(Math.random()*2138);
got.getCharacter(random)
.then((res) => {
console.log(res.name)
this.setState({
name: res.name
})
})
}
render() {
return (
<div className="random-block rounded">
<button onClick={this.getData}>Click</button>
<h4>Random Character: {this.state.name}</h4>
</div>
);
}
}
File GotService.js
export default class GotService {
constructor(){
this._apiBase = 'https://www.anapioficeandfire.com/api'
}
async serverRun (url) {
const res = await fetch(`${this._apiBase}${url}`);
if (!res.ok) {
throw new Error(`${res.status}`)
}
return await res.json();
}
getCharacter(id) {
return this.serverRun(`/characters/${id}`)
}
}
Why when I click on the button I get a response in the console:
Rohanne
Uncaught (in promise) TypeError: Cannot read properties of undefined
Why does the console output Rohanne, and the value of Rohanne is not written to state, but is displayed as undefined?
thank for helping