Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot read property 'length' of undefined react

TypeError: Cannot read property 'length' of undefined

That's what the compiler says when I run my react app. What I do need to do with this?

request = (start,end) => {
   if(this.state.teams.length < 1){
       axios.get(`${ URL }/teams`)
       .then( response => {
           this.setState({
               teams:response.data
           })
       })
   }

    axios.get(`${ URL }/articles?_start=${start}&_end=${end}`)
    .then( response => {
        this.setState({
            items:[...this.state.items,...response.data]
        })
    })
}
like image 965
Kuba Kluzniak Avatar asked Jul 09 '18 17:07

Kuba Kluzniak


3 Answers

I would suggest to check first if the props is undefined or empty or even declared.

for example:-

    const card = props && props.cards && props.cards.length > 0 ?
        props.cards.map((card, i) => {
            return (
                <card >
            )
        }) : '';

And return your card.

like image 87
Hasan Zahran Avatar answered Sep 23 '22 00:09

Hasan Zahran


I would suggest using a check to see if "teams" is undefined before trying to get the length.

if (value === undefined) {
    // value is undefined
}
like image 29
Bekah Saugen Avatar answered Sep 23 '22 00:09

Bekah Saugen


Be sure that the teams value of your component's state is initialized with an array value like this :

class MyComponent extends React.Component {

    state: {
      teams: [],
    };
}
like image 21
thomas.winckell Avatar answered Sep 24 '22 00:09

thomas.winckell