Search code examples
reactjsrenderer

react render variable undefined


for some reason that i dont understand, i cant seem to fetch a state value in my renderer, at first i thought it was a scoping issue, but even after changing to var, my variable is undefined.

constructor(props) {
        super(props);
        this.state = {
            stuff: {}
        };

 componentDidMount(){
                
            this.getatuff.then( (result) =>{
                    this.setState({
                        stuff: result.items[0]
                });
            });
        console.log('REACT Coveo component DOM loaded');

    }
    render() {
        var ReactMarkdown = require('react-markdown');
        var project = this.state.stuff;
        
        debugger;
        if(!Object.entries(project).length === 0){
            var asd = project.body[1].value; <---UNDEFINED
            return (
                <div className="block"> 
                    <ReactMarkdown source={asd} />
                    </div>               
            );
        }

enter image description here

why is my Object array value undefined in the renderer?

Note: both const variables in the screenshot were changed to var, and the behavior persists.


Solution

  • You'd need to define state inside your class, or inside your constructor():

    constructor(props) {
      super(props);
    
      this.state = {
        project: // something
      }
    }
    
    componentDidMount() { 
      // etc.