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]
        })
    })
}
1

4 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.

2

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

if (value === undefined) {
    // value is undefined
}

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: [],
    };
}

Probably because you're having a variable that is supposed to contain an array but is undefined when referencing the length property. Try searching for .length in your editor and create an empty array if it's not initialized:

if ((arr || []).length > 0) {
  // do something
}

// or

if (arr?.length > 0) {
  // do something
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest