How to display all single data from database? This is React - mysql

This is the profile page it shows all the data but I want to show only one data database after login?
function
function Profile() {
const [studentList, setStudentList] = useState([]);
let navigate = useNavigate();
const getStudent = () => {
Axios.get("http://localhost:3001/students").then((response) => {
setStudentList(response.data);
});
};
Display
return (
<div className="students">
<button onClick={getStudent}>Show Students</button>
<h3>
</h3>
{studentList.map((val, key) => {
return (
<div className="student">
<div>
<h3>Email: {val.email}</h3>
<h3>Password: {val.password}</h3>
<h3>Student Number: {val.student_num}</h3>
</div>
Get data from Database
app.get("/students", (req, res) => {
db.query("SELECT * FROM student", (err, result) => {
if (err) {
console.log(err);
} else {
res.send(result);
}
});
});

Related

Mongoose updating and fetching in the same request

I have the following mongoose "update" path:
app.put('/update', async (req, res) => {
const newTaskName = req.body.todoName
const newDays = req.body.days
const id = req.body.id
try {
await TodoModel.findById(id, async (err, updatedTodo) => {
updatedTodo.todoName = newTaskName
updatedTodo.daysToDo = newDays
await updatedTodo.save()
res.send("updated")
})
} catch(err) {
console.log(err)
}
})
Separately I have a path that returns all data from the Mongo table:
app.get('/read', async (req, res) => {
TodoModel.find({}, (err, result) => {
if (err) {
res.send(err)
}
res.send(result)
})
})
How can I both update and send back the full updated list within the response?
Separate question, not necessary to answer, but would be nice - perhaps this approach is all wrong? some background:
In my MERN app I am calling to add an item to a list and then want to immediately render the updated list as currently read from the database, since I don't want to assume the insertion was successful
I tried using some asynchronous workarounds with no luck
Fixed!
Upon further inspection of Mongoose documentation, I found that by using the findOneAndUpdate method instead of findById, I am able to utilize a callback that will return the updated item:
app.put('/update', async (req, res) => {
const id = req.body.id
let updateSet = req.body
delete updateSet.id
try {
ShoppingModel.findOneAndUpdate({ _id: id }, { $set: updateSet }, { new: true }, (err, doc) => {
if (err) return console.log(err)
res.send(doc)
})
} catch (err) {
console.log(err)
}
})

Confused about changing state in a certain way

I have a page in NextJS for editing an sql row and sending it back. I have fetched all the rows from the table and then have set the state to be the single row which matches the query parameter in the useRouter hook. Now, after I have edited the data in the row, what is a good way to POST it back to the backend?
Below is my React code:
import { React, useEffect, useState } from "react";
import { useRouter } from "next/dist/client/router";
const axios = require("axios");
export default function Edit() {
const [data, setData] = useState([]);
const router = useRouter();
const onSubmitHandler = (e) => {
e.preventDefault();
axios.post("/api/cards", data);
};
useEffect(() => {
const fetchData = async () => {
await axios
.get("/api/cards")
.then((res) => {
if (res.data) {
res.data.map((element) => {
if (element.ID == router.query.card) {
setData(element);
return;
}
return;
});
}
})
.catch((err) => {
console.log(err);
});
};
if (router.isReady) {
fetchData();
}
}, [router.isReady, router.query.card]);
return (
<form onSubmit={onSubmitHandler}>
<label htmlFor="front">Front</label>
<input
defaultValue={data.Front}
id="front"
onChange={(e) => setData({ ...data, Front: e.target.value })}
></input>
<label htmlFor="back">Back</label>
<input
defaultValue={data.Back}
id="back"
onChange={(e) => setData({ ...data, Back: e.target.value })}
></input>
<button type="submit">Add Word</button>
</form>
);
}
Below is my backend code
if (req.method === "POST") {
const { front, back, type } = req.body.data;
const id = uuidv4();
db.query(
`INSERT INTO deck VALUES('${front}', '${back}', '${type}', '${id}')`,
(err, rows, fields) => {
if (!err) {
res.json(rows);
} else {
console.log(err);
}
}
);
}
Its good to post the edited data after submiting the form..
const onSubmitHandler = async (e) => {
e.preventDefault();
try {
await axios.post("/api/cards", data);
// react-toast or something like that to indicate the ui the form is updated
// then the control flow of the application
} catch (error){
console.error(error)
}
};
One thing I notice over here is you're using POST for the update. Try HTTP PUT instead of POST.
And regarding your answer: You can send modified data in your API call like you're already maintaining the state of the updated data. Then you can just send that row to the API call and handled that in your backend code.
const onSubmitHandler = (e) => {
e.preventDefault();
axios.put("/api/cards/:id", data); // modify the API URL and append dynamic ID of the record.
};

react js show image from mysql with multer

I'm working currently on a website where a user should be able to upload an image.
But unfortunately I get this error: GET c:\fakepath\nfr.jpeg net::ERR_UNKNOWN_URL_SCHEME
I'm using Express and multer.
Here's the code for my backend:
const storage = multer.diskStorage({
destination: (req, file, callBack) => {
callBack(null, './public/') // './public/images/' directory name where save the file
},
filename: (req, file, callBack) => {
callBack(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
}
})
const upload = multer({
storage: storage
})
app.get('/api/get', (req, res) => {
db.query(
'SELECT * FROM users',
(err, result) => {
if (err) {
console.log(err)
}
res.send(result)
}
)
})
app.post('/api/create', (upload.single('image')), (req, res) => {
const title = req.body.title
const post = req.body.post
const imagesrc = req.body.image
db.query(
'INSERT INTO users (title, post_text, images) VALUES (?,?,?)', [title, post, imagesrc],
(err, result) => {
if (err) {
console.log(err)
}
console.log(result)
}
)
})
Here's my code for the frontend:
const [title, setTitle] = useState('')
const [post, setPost] = useState('')
const [image, setImage] = useState('')
const submitPost = () => {
axios.post('http://localhost:3001/api/create', {
title: title,
post: post,
image: image,
}).then(r => {
console.log(r)
}).catch(err => {
console.log(err)
})
}
const [postList, setPostList] = useState([])
useEffect(() => {
axios.get('http://localhost:3001/api/get').then((data) => {
console.log(data)
setPostList(data.data)
})
}, [])
<div className="createPost">
<input
type='file'
name='file'
onChange={(e) => {
setImage(e.target.value)
}}
/>
<img src={image}/>
<input
type="text"
placeholder="Titel"
onChange={(e) => {
setTitle(e.target.value)
}}
/>
<input
type="text"
placeholder="Post"
onChange={(e) => {
setPost(e.target.value)
}}
/>
</div>
<div className="postButton">
<button onClick={submitPost}>speichern</button>
</div>
<div className="post">
{postList.map((val, key) => {
return (
<div className="Post" key={key}>
<h1>{val.title}</h1>
{/*<p>{val.username}</p>*/}
<p>{val.post_text}</p>
<p>{val.image}</p>
<button className="kaufenButton" onClick={toggleModalUnt}>Jetzt testen</button>
</div>
)
})}
</div>
If you need anything else, let me know it.
Thanks in advance.

How to add Promise value in render() in node js

router.get('/top-website', function (req, res, next) {
// console.log(topSites)
connection.query("SELECT * FROM topsites LIMIT 5", function (err, results, fields) {
// const url =this.rootDomain;
results.forEach(function (item) {
console.log(item.rootDomain)
linkPreview(item.rootDomain)
.then(resp => {
console.log(resp)
res.render('top-website', { sitedata: results,fn:resp });
//console.log(resp)
})
})
})
})
i want to get value resp in render but im getting error,

how to correctly get (axios) by UUID , ReactJs NodeJs

I would like to explain my problem of the day.
currently i am logging in,
I am in my profile, and here I would like to display my name.
the following code works correctly, only it shows me all the use registered in my database.
and I would only like to be able to display the correct name which corresponds to the UID in my database
How can I fix this issue?
that is my get and return
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
data:[]
};
}
getRandom = async () => {
const res = await axios.get(
"https://joke.fr/api/profil"
);
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
}
render() {
return (
<div>
{this.state.data.map(data => <p>{data.name}</p>)}
</div>
)
}
}
export default Profile;
that is my route is bdd
app.get('/api/profil', (req, res) => {
connection.query('SELECT * from profil' , (err, results) => {
if (err) {
console.log(err);
return res.status(500).send('Erreur lors de la récupération des employés');
} else {
console.log(results);
return res.json(results);
}
});
});
and last one is my BDD schéma.
{
"id": 62,
"name": "neff",
"uid": "dycjibu96zgmzc0KpGAqxKiUsMu2"
}
You would need another parameter in your app.get. I suppose when user logged in to your app, you store their UID. If that's the case, you can use:
app.get('api/profil/:id', (req, res) => {
const userId = req.params.id
connection.query(`SELECT * from profil WHERE id = ${userId}` , (err, results) => {
if (err) {
console.log(err);
return res.status(500).send('Erreur lors de la récupération des employés');
} else {
console.log(results);
return res.json(results);
}
});
})
But I would recommend something like body-parser to sanitise your SQL request though.
Since you are logged in then probably you have the UUID or name in the browser saved in the local storage (this is the simplest approach). This means on your backend you should send a GET request to get 1 profile based on the UUID.
Server Side Code
app.get('/api/profil/:name', (req, res) => {
const { name } = req.params;
connection.query(`SELECT * from profil where name=${name}`, (err, results) => {
if (err) {
console.log(err);
return res.status(500).send('Erreur lors de la récupération des employés');
} else {
// This should be an object
console.log(results); // This should be an object like {"id": 62, "name": "authUser"}
return res.json(results);
}
});
});
Client Side Code
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
userProfile: null
};
}
getUserProfile = async (userName) => {
// Get the profile by passing the id to the URL.
// Side note, you should handle errors here but for simplicity lets skip it.
const res = await axios.get(
`https://joke.fr/api/profil/${userName}`
);
// res.data should be an object like {"id": 62, "name": "authUser"}
this.setState({ userProfile: res.data });
}
componentDidMount() {
// You should have the id of the user after login
// Let me assume you stored it in localstorage
const user = localStorage.getItem("user");
if (user) {
const { id, name } = JSON.parse(user);
// You can skip the localstorage part if you store the user's details in a different way and jump here by passing the ID/name to this function
this.getUserProfile(name);
}
}
render() {
const { userProfile } = this.state;
return (
<div>
{userProfile ? userProfile.name : "No user name"}
</div>
)
}
}
export default Profile;