0

I'm trying to show some information about a user in front-end, but I don't know why is not showing anything. If I access the server using localhost:8080/api/user I can see the information in an empty page (is just a dummy database that I had), but I can't print them in my content page, my code recognizes the list as being empty. I'm a beginner and I just started using React, Node.js, and Express.

UserStatus.js

import React from 'react';

class UserStatus extends React.Component {

  constructor(props){
    super(props);
    this.state = {
      list: []
    }
  }
  // Fetch the list on first mount
  componentDidMount() {
  }
  // Retrieves the list of items from the Express app
  getList = () => {
    fetch('/api/user')
    .then(res => res.json())
    .then(list => this.setState({ list })
    )
  }

  render() {
    const { list } = this.state;
    return (
      <div className="App">
        <h1>User Status</h1>
        {/* Check to see if any items are found*/}
        {list.length ? (
          <div>
            {/* Render the list of items */}
            {list.map((item) => {
              return(
                <div>
                  {item}
                </div>
              );
            })}
          </div>
        ) : (
          <div>
            <h2>No List Users Found</h2>
          </div>
        )
      }
      </div>
    );
  }
}
export default UserStatus

server.js

//Initiallising node modules
var express = require("express");
var bodyParser = require("body-parser");
var sql = require("mssql");
var app = express();

// Body Parser Middleware
app.use(bodyParser.json());

//CORS Middleware
app.use(function (req, res, next) {
    //Enabling CORS 
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, contentType,Content-Type, Accept, Authorization");
    next();
});

//Setting up server
var server = app.listen(process.env.PORT || 8080, function () {
    var port = server.address().port;
    console.log("App now running on port", port);
});

//Initiallising connection string
var dbConfig = {
    user: '---',
    password: '---',
    server: '----',
    database: '---'
};

//Function to connect to database and execute query
var executeQuery = function (query, res) {
    sql.connect(dbConfig, function (err) {
        if (err) {
            console.log("Error while connecting database :- " + err);
            res.send(err);
        } else {
            // create Request object
            var request = new sql.Request();
            // query to the database
            request.query(query, function (err, ress) {
                if (err) {
                    console.log("Error while querying database :- " + err);
                    res.send(err);
                } else {
                    res.json(ress);
                }
            });
        }
    });
}

//GET API
app.get("/api/user", function (req, res) {
    var query = "select * from Machine";
    executeQuery(query, res);
});

//POST API
app.post("/api/user", function (req, res) {
    var query = "INSERT INTO [user] (Name,Email,Password) VALUES (req.body.Name,req.body.Email,req.body.Password)";
    executeQuery(res, query);
});

//PUT API
app.put("/api/user/:id", function (req, res) {
    var query = "UPDATE [user] SET Name= " + req.body.Name + " , Email=  " + req.body.Email + "  WHERE Id= " + req.params.id;
    executeQuery(res, query);
});

// DELETE API
app.delete("/api/user /:id", function (req, res) {
    var query = "DELETE FROM [user] WHERE Id=" + req.params.id;
    executeQuery(res, query);
});

2 Answers 2

2

To debug you can set breakpoints or use console.log or some other console method. First you can check your fetch response:

getList = () => {
  fetch('/api/user')
  .then(res => {
    console.log(res) // is it a string or is it already json? What is the data structure?
    return res.json()
  })
  .then(list => this.setState({ list }))
  .catch(err => console.error(err)) // you should handle errors
 }

Also you should catch errors. It seems to me you are returning a dataset with a toplevel 'recordset' attribute. So you probably have to do: return res.json().recordset

Sign up to request clarification or add additional context in comments.

Comments

0

First of all, list.length is just a number you need to check if the array is greater than zero

list.length > 0 

Secondly, Check to see if the data is being received from the backend

   getList = async () => {
    try{
     let res =  await fetch('/api/user');
     console.log(res);
    } catch (err) {
     console.log(err);
    }        
   }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.