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?
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('')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With