Reputation: 1759
I faced a weird problem, I found the answer, however I want to know the reason behind the scene.
I have a react
component which sends request toward server and after getting the result back, set it to the states of the component.
class Featured extends React.Component{
constructor(props){
super(props);
this.state = {
data : ['', ''],
error: null,
}
}
componentDidMount(){
axios.get('/api/featured')
.then(res=>{
let dataClone = [2];
console.log('before');
res.data.map((dt,i)=>{
dataClone[i] = dt;
});
this.setState({
data : dataClone
})
})
.catch(err=>{this.setState({error: err}); errorHandling(err)});
}
render(){
if(!this.state.error){
return(
<div>data: {this.state.data[1].title}</div>
)
}
else {
return (<div className='text-center text-warning'>There is some error loading the featured</div>)
}
}
}
here's the data which sent back :
{
title : 'how to be a good programmer?',
subtitle: 'I was wondering how can i be a good programer after 10 years experience',
author : 'hamid mortazavi',
date : new Date().toLocaleDateString(),
},
{
title : 'Why are you alone?',
subtitle: 'this is going to be a long story from here, but bear with me...',
author : 'shahin ghasemi',
date : new Date().toLocaleDateString(),
}
This works correctly, however if I change the way I've done initialization for data
state, it does not work.
for example this three ways does not work:
this.state = {
//1:
data : new Array(2),
//2:
data : [],
//3:
data : [2]
}
none of these works, and when I want to show this.state.data[1].title
for example, it does not work, and throw me Uncaught TypeError: Cannot read property 'title' of undefined
. What surprises me is there is no problem displaying this.state.data[0].title
and it seems the problem is the index.
As I said now I found the solution but it takes me 1 hour to solve that. I just want to know the reason and why ?
Upvotes: 5
Views: 10119
Reputation: 81
In the case that is not working you are setting the initial state.data to an empty array ( or in the last case to an array with one number 2 in it). When you call this.state.data[1].title
you are trying to access a property on undefined
, which give` you a null point error.
In the case that is working for you, you are trying access the property title
on an empty string, which will be undefined, but it doesn't error because the thing you're trying to find the title of (the empty string) is not undefined.
Upvotes: 0
Reputation: 3172
This is not a problem of React but a problem of array items being undefined.
In your first example where you don't see the error, you actually defined the value of the 2 items in the state array by doing this
data : ['', ''],
This way, the value of data[0] and data[1] always exist and unless set by data response from server, will always have at least a value of an empty string.
In your second example, your data object is just a blank array of either no items ([]), 1 item ([2]), or 2 items (new Array(2)). Even with new Array(2), your data object items doesn't have a value defined. Try running this in your console:
x = new Array(2)
x[0] // will return undefined
x[1] // will return undefined
Upvotes: 1