'passing data from node js to react js

I'm trying to pass data from node to react but getting data in text form like res.text() perfectly but unable to get data in object form. Have tried to render with map as well but not working.

REACT JS

import React, { Component } from 'react'
import axios from 'axios';
export default class List extends Component {
  constructor(props)
  {
    super(props);
    this.state={apiResponse:[]};
    
  }
callAPI()
  {
    fetch("http://localhost:9000/testAPI")
    .then( (res) => res.json())   
    .then( (json) => {this.setState({apiResponse: json});});
  }

  componentWillMount()
  {
    this.callAPI();
  }

  render() {
    return (
      <div>
        <h1>{this.state.apiResponse}</h1>
      </div>
    )
  }
}

NODE JS

router.get("/", function (req, res) {
  MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var dbo = db.db("to-do");
    // var query = { address: "Park Lane 38" };
    dbo
      .collection("to-do")
      .find({})
      .toArray(function (err, result) {
        if (err) throw err;
        console.log(result);
        // res.send((result))
        db.close();
      });
  });
  // console.log();
});
   


Solution 1:[1]

First of all you are not sending response in NodeJS Get Request

router.get("/", function (req, res) {
  MongoClient.connect(url, function (err, db) {
  if (err) throw err;
  var dbo = db.db("to-do");
  // var query = { address: "Park Lane 38" };
  dbo
   .collection("to-do")
   .find({})
   .toArray(function (err, result) {
     if (err) throw err;
     res.send((result))
     db.close();
   });
});

});

And then at React Side its a good practice to fetch API results in componentDidMount function instead of componentWillMount. And if API Response is array/object type then if you only want to display the results in the React, use JSON.stringify(object) like:

import React, { Component } from 'react'
import axios from 'axios';
export default class List extends Component {
  constructor(props)
  {
    super(props);
    this.state={apiResponse:[]};
    
  }
callAPI()
  {
    fetch("http://localhost:9000/testAPI")
    .then( (res) => res.json())   
    .then( (json) => {this.setState({apiResponse: json});});
  }

  componentWillMount()
  {
    this.callAPI();
  }

  render() {
    return (
      <div>
    <h1>{JSON.stringify(this.state.apiResponse)}</h1>
      </div>
    )
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Asad Haroon