tyjanii hassan
tyjanii hassan

Reputation: 65

Cannot read length property of undefined

i am trying to render the length of the state to the screen and it keeps telling me, cannot read length property of undefined. When i tried logging the value of state to the console, at first it was undefined, after running a search the value updated and there were 5 items in the array. problem now is when it updates, it does not update on the screen, either that or it flat out crashes.

export default class App extends Component {
    state={
       vidoes:[]
   };

    onTermSubmit = async term =>{
   const response = await youtube.get('/search',{
        params:{
            q:term,
        }
    });

    this.setState({videos:response.data.items})
   };



    render() {
        console.log(this.state.videos)
        return (
            <div className="ui container">
                <SearchBar onFormSubmit={this.onTermSubmit}/>
                {this.state.vidoes.length}
            </div>
        )
    }

The ultimate goal is to have the length of state render on the screen and now that it is being described as undefined, it will be impossible to loop throght it.

Upvotes: 0

Views: 101

Answers (2)

user11910739
user11910739

Reputation:

There are some typo videos. Please change it to this.state.videos.length in render method.

render() {
        console.log(this.state.videos)
        return (
            <div className="ui container">
                <SearchBar onFormSubmit={this.onTermSubmit}/>
                {this.state.videos.length}
            </div>
        )
    }

Hope this will work for you.

Upvotes: 1

Dixit Savaliya
Dixit Savaliya

Reputation: 413

Try This,

  export default class App extends Component {
            state={
               videos:[]
           };

            onTermSubmit = async term =>{
           const response = await youtube.get('/search',{
                params:{
                    q:term,
                }
            });

            this.setState({videos:response.data.items})
           };



            render() {
                console.log(this.state.videos)
                return (
                    <div className="ui container">
                        <SearchBar onFormSubmit={this.onTermSubmit}/>
                        {this.state.videos.length}
                    </div>
                )
            }

Upvotes: 0

Related Questions