I figured out how to make a request to SQL server and post as JSON on the server side. I'm wondering how I can pull that data into the react side.
Server.js:
let pullTable = require('./actions/pullTable.js');
var express = require('express');
var app = express();
app.get('/', async (req, res, next) => {
try {
const result = await pullTable.pullTable();
return res.status(200).json(result);
} catch (error) {
next(error);
}
});
app.listen(5000, () => {console.log('Server is running..')});
SQL Request - pullTable.js:
var sql = require("mssql");
var express = require('express');
var app = express();
// config for your database
var config = {
user: 'user',
password: 'pass',
server: 'localhost',
database: 'Master'
};
const pullTable = async () => {
try {
const pool = await sql.connect(config);
const sqlQuery = 'SELECT * FROM Persons';
const result = await pool.request().query(sqlQuery);
return result.recordset;
} catch (err) {
throw err;
}
};
exports.pullTable = pullTable;
The code works fine up to here. I look at port 5000 and can see the JSON data being displayed from my server. Just not sure how to get this into React. This is my attempt at the react side (not including the App.js file - don't need help with that):
getData.js:
import React, { Component } from 'react';
class getData extends Component {
constructor(){
super();
this.state={
data:[],
}
}
componentDidMount(){
fetch('http://localhost:5000')
.then((Response)=>Response.json())
.then((findresponse)=>
{
this.setState({
data:findresponse,
});
});
}
render() {
return (
<div>
{
this.state.data.map((dynamicData)=>
<div>
<span>{dynamicData.LastName} </span>
<span>{dynamicData.FirstName}</span>
</div>
)
}
</div>
);
}
}
export default getData;
Just looking to display the first and last name of people in that SQL table.
[{ "Firstname": "John", "Lastname": "Doe" }, ... ], you should see the list of records from the database.