I Have a JSON DB and a React Component that fetch these datas. Here is my JSON DB:
{
"houses": [
{
"id": 1,
"name": "house 1"
},
{
"id": 2,
"name": "house 2"
},
{
"id": 3,
"name": "house 3"
}
]
}
It is fetching by a ReactJS Component. When I do console.log() inside of a Axios' loop it works successfully. But inside of the render method it isn't working. How can I solve it?
class Houses extends Component {
constructor(props) {
super(props);
this.state = {
index:0,
currentHouse:[]
};
}
componentDidMount() {
axios.get(URL_HOUSES)
.then(res => {
this.setState({ index:0 })
this.setState({ currentHouse: res.data})
//Here is working! It is returning the index and the current house's name
console.log('index:' + this.state.index)
console.log(
'Name of the current house:' +
this.state.currentHouse[this.state.index].name
)
}
render() {
return (
<div>
//Here isn't working. It is returning an error message:
//TypeError: Cannot read property '0' of undefined
<h3>{this.state.currentHouse[this.state.index].name}</h3>
</div>
);
}
}
export default Houses
TL;DR check initial currentHouse array before displaying it in the render method.
On the initial render of your component, there are no elements in the currentHouse
array.
So when your component tried to print out your statement this.state.currentHouse[this.state.index].name
, what it's actually trying to do is find the 0th position of an empty array []
. This will evaluate to undefined
.
An option to fix this is set an initial value to the currentHouse array in the state, or check to see if there are values in the array. For example:
<h3>{this.state.currentHouse.length && this.state.currentHouse[this.state.index].name}</h3>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments