Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

Tags:

reactjs

just trying to render a list of items obtained from my backend but getting this error indicating it's undefined. However, when I check the console log I can see that the component's state definitely has 5 items in the array.

class PubSubTopics extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            pubsubtopics: ['one', 'two', 'three'],
        }
    }

    componentDidMount() {
        this.callBackEndAPI()
            .then(res =>
                this.setState({pubsubtopics: res.express}))
            .catch(err => console.log(err));
        console.log('after setting state');
        console.log(this.state.pubsubtopics);
    }


    callBackEndAPI = async () => {
        const response = await fetch('/listtopics');
        const body = await response.json();

        if(response.status !== 200){
            throw Error(body.message)
        }
        console.log('after API responded');
        console.log(body.topics);
        return body.topics;
    }
    render(){
        const list = [];
        for(const[index, value] of this.state.pubsubtopics){
            list.push(<li key={index}>{value}</li>)
        }
        return(
            <div>
                <ul>
                    {list}
                </ul>
                <button onDoubleClick={this.handleClick}/>
            </div>
        )
    }
}

Console log:

after setting state
index.js:21 (3) ["one", "two", "three"]
index.js:32 after API responded
index.js:33 (5) [{…}, {…}, {…}, {…}, {…}]

Any idea why it's saying this.state.pubsubtopics is undefined?

like image 614
Michael Avatar asked Mar 22 '19 22:03

Michael


1 Answers

check all the brackets used in the code at specified line number.e.g.:
in my case this was throwing error -

const [query, setQuery] = useState['']

When i corrected this,

const [query, setQuery] = useState('')

This was working fine for me.
Please check if this fixes your problem.
like image 71
Sumit Jadiya Avatar answered Sep 16 '22 12:09

Sumit Jadiya