So i set up a database which is running and having 31 objects in it.
Now i connected the database to my frontend and log it there in the console, as you can see here:
Now lets say i want to display the text from the object with the id : 1 there. Which would be in this case "Source". It should be displayed under my h1 field which says "Show me Text from object with id 1".
How do i achieve this?
Here is my code:
Backend (index.js):
const express = require('express');
const bodyParser = require ('body-parser');
const app = express();
const mysql = require('mysql');
const cors = require('cors');
const db = mysql.createPool({
host: "localhost",
user: "root",
password:"mypassword",
database:'myDatabase',
});
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({extended: true}))
app.get('/api/get', (req,res)=>{
const sqlSelect = 'SELECT * FROM myDatabase.signaldb;'
db.query(sqlSelect, (err,result)=> {
res.send(result);
if (err) console.log(err);
})
})
app.listen(3001, () => {
console.log("running on port 3001")
})
Frontend (App.js)
import Axios from 'axios';
import React, {useState, useEffect} from "react";
const App = () => {
const [signalList, setsignalList] = useState([]);
useEffect(()=> {
Axios.get("http://localhost:3001/api/get").then((response) =>
{
//log data
console.log("response data: ");
console.log(response.data);
setsignalList(response.data)
})
});
return (
<div>
<h1>Show me Text from object with id 1</h1>
</div>
);
}
export default App;
You can use forEach/map/filter to loop within the list of elements and when it finds the one that matches the id that you are looking for, render it.
Filter solution:
return (
<div>
<h1>{signalList.filter(obj => obj.id == yourId)[0].text}</h1>
</div>
);
The filter is the easiest straight-on solution, but maybe if you want to do something with the other elements that you are not rendering because the ID isn't the one you are looking for, a map loop would be the solution.
Map solution:
return (
<div>
{signalList ? signalList.map(obj => obj.id == yourId ? <h1>{obj.text}</h1>) : DO SOMETHING ELSE}
</div>
);
you can use map function
const [signalList, setsignalList] = useState([]);
useEffect(()=> {
Axios.get("http://localhost:3001/api/get").then((response) =>
{
//log data
console.log("response data: ");
console.log(response.data);
setsignalList(response.data)
})
//please add empty array if you want to just execute this function once on mount
},[]);
return (
<div>
<h1>{ signalList.map((e,i)=> e.id==1 ? e.text : '' }</h1>
</div>
);
}
Assuming your IDs are distinct you can do like this. yourId is what you want to search for.
return (
<div>
<h1>(signalList.filter(obj => obj.id == yourId))[0].text)</h1>
</div>
);