Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to initialize states of array with unknown length in reactJS?

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 ?

like image 375
Shahin Ghasemi Avatar asked Nov 07 '22 03:11

Shahin Ghasemi


1 Answers

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
like image 71
Arielle Nguyen Avatar answered Nov 14 '22 21:11

Arielle Nguyen