Search code examples
node.jsreactjscomponentsjsx

'TypeError: this is undefined' occurs when using members of a class from a functional component


I am trying to pass data to a ReactJS component using NodeJS by making a simple NodeJS API hosted in a separate localhost (:9000). But I'm getting an error.

TypeError: this is undefined

My belief is that this error occurred due to using 'this' inside the functional component. But I cannot find a way to resolve this problem.

The code which has the error:

import React from 'react';
import ReactDOM from 'react-dom';

class News extends React.Component{


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

   }

   callAPI(){
      fetch("http://localhost:9000/testAPI")
      .then(res => res.text ())
      .then(res => this.setState({apiResponse: res}));
      
      
   }

   componentWillMount(){
      this.callAPI();
   }
}

function Newsexport() {
 return (
    <div class="container1">
       <h1>IT WORKS YO!</h1>
      <p>{this.state.apiResponse}</p> 
    </div>
  )
};

export default Newsexport;

The code of the simple API hosted with NodeJS (/api/routes/testAPI.js)

var express = require("express");
var router=express.Router();

router.get("/", function(req,res,next){
    res.send("API is working");

});

module.exports=router;

Solution

  • You are using this in a functional component which is wrong. Also you are setting state in one component and expecting the value in another component. Instead combine the two components like below -

     class News extends React.Component{
    
        constructor (props){
          super(props);
          this.state={apiResponse:""};
        }
    
        callAPI = () => {
          fetch("http://localhost:9000/testAPI")
            .then(res => res.text ())
            .then(res => this.setState({apiResponse: res}));
        }
    
        componentWillMount(){
          this.callAPI();
        }
    
        render() {
          return (
            <div class="container1">
              <h1>IT WORKS YO!</h1>
              <p>{this.state.apiResponse}</p> 
            </div>
          )
        }
      }
      export default News;
    

    Let me know if this helps.