5
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
  • 2
    I would assume then that you dont have a value for teams. Try checking if this.state.teams has a value. Commented Jul 9, 2018 at 17:50

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This works gratefully, But do we have any generic method to use these flags. because i have 20 place where am using this flag for single component and it makes component lengthy and messy
@HidaytRahman You can do it with useEffect hook to update specific "state/flag" after getting response from the API for example.
4

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

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

Comments

3

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

Comments

0

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
}

Comments

0

This issue happens especially in react or react native, just add a question sign e.g,

{title?.length>20? title?.substring(0,20)+'...':title}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.