I would like to explain my problem of the day.
i think it's harder than usual, so let me explain
here i start by getting a get
getRandom = async () => {
const res = await axios.get(
entrypoint + "/alluserpls"
)
this.setState({ data: res.data })
}
componentDidMount() {
this.getRandom()
}
here is my method for delete
handleSubmit = (e) => {
e.preventDefault();
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));
}
then I map it
render() {
let datas = this.state.data.map((datass, index) => {
return (
<Col sm="12" key={index}>
<form onSubmit={this.handleSubmit}>
<button type="submit">Delete</button>
</form>
<div>{datass.name}</div>
</Col>
then i return the result on my map
return (
<div>
{datas}
</div>
so works correctly ,
but the problem is the following when I want to delete only 1 CARD it deletes all my BDD
Here is my routes on BDD
app.delete('/api/alluserpls', (req, res, ) => {
const formData = req.body;
connection.query('DELETE FROM alluserpls SET ?', formData, err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
I would like that when I click on delete it only deletes the card and not all of my database.
How can I fix this issue?
Here is one way to do it, assign the id of the user to button id attribute field and then call the delete API with the user id
handleSubmit = (e, id) => {
e.preventDefault();
const userIdData = { id };
const config = {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(userIdData),
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
} else {
alert(`ajouté avec l'ID ${res}!`);
}
}).catch(e => {
console.error(e);
}).finally(() => this.setState({ redirect: true }));
, in the render method you can pass the id as variable to the handleSubmit function
render() {
let datas = this.state.data.map((datass, index) => {
return (
<Col sm="12" key={index}>
<form onSubmit={(e) => this.handleSubmit(e, datass.id)}>
<button type="submit">Delete</button>
</form>
<div>{datass.name}</div>
</Col>
and in the backend you can get the id and delete only the particular user
app.delete('/api/alluserpls', (req, res, ) => {
const formData = req.body;
const userId = req.body.id;
const deleteQuery = `DELETE from alluserpls WHERE id = ${userId}`;
connection.query(deleteQuery, err => {
if (err) {
res.status(500).send("Erreur lors de la modification des users");
} else {
res.sendStatus(200);
}
});
});
Related
How To Refresh User data coming from a variable route? I have a variable called "user" which is coming from a different screen by "react navigation" route that user variable contains all the data I need, So How can I reload that user variable data after "Set follow" is true without fetching anything because "user" variable data is coming is fetching from a different screen?
Code:
const Profile = ({ navigation, route }) => {
const { user } = route.params; // HERE IS THAT USER VAR
const [issameuser, setIssameuser] = useState(false)
const [follow, SetFollow] = useState(false)
const isMyProfile = async (otherprofile) => {
AsyncStorage.getItem('user').then((loggeduser) => {
const loggeduserobj = JSON.parse(loggeduser)
if (loggeduserobj.user.username == otherprofile[0].username) {
setIssameuser(true)
}
else {
setIssameuser(false)
}
})
}
const CheckFollow = async (otherprofile) => {
AsyncStorage.getItem('user')
.then(loggeduser => {
const loggeduserobj = JSON.parse(loggeduser);
return fetch('http://10.0.2.2:3000/checkfollow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
followfrom: loggeduserobj.user.username, followto: otherprofile[0].username
})
})
})
.then(res => res.json())
.then(data => {
if (data.message == "User in following list") {
SetFollow(true)
} else if (data.message == "User not in following list") {
SetFollow(false)
} else {
alert('Please Try Again!')
}
})
}
const FollowUser = async (otherprofile) => {
const loggeduser = await AsyncStorage.getItem('user')
const loggeduserobj = JSON.parse(loggeduser)
fetch('http://10.0.2.2:3000/Follow', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
followfrom: loggeduserobj.user.username, followto: otherprofile[0].username
})
})
.then(res => res.json())
.then(data => {
if (data.message == "User Followed") {
SetFollow(true) // HERE I WANT TO RE-LOAD USER VAR DATA
}
else {
alert("Pleas Try Again")
}
})
}
useEffect(() => {
isMyProfile(user)
CheckFollow(user)
},)
}
is their any method to do that or i need to use socketio?
I've managed to redirect a page after a DELETE request to the home GET route, but the page isn't actually refreshing (i.e. the deleted item still appears) and it isn't until I manually refresh the page that it is removed. I've done some console.logs and the item has definitely been deleted by the time it has redirected to .get('/'). Any ideas why this isn't working?
app.js - routes only
app.route('/')
.get((req, res) => {
connection.query('SELECT * FROM todos', (err, results) => {
if (err) throw err;
console.log(results);
console.log('Todos read from database');
res.render('home', { results: results });
});
})
.post((req, res) => {
const todoItem = req.body.todo;
connection.query('INSERT INTO todos (todo) VALUES (?)', todoItem, err => {
if (err) throw err;
console.log('Todo inserted into database.');
res.redirect('/');
});
})
.delete((req, res) => {
const todo = req.body.todoItem;
connection.query('DELETE FROM todos WHERE todo=?', todo, err => {
if (err) throw err;
console.log('Todo deleted from database.');
});
res.redirect(303, '/');
});
client.js
'use strict';
let todoItems = document.getElementsByClassName('todo-item');
for (let i = 0; i < todoItems.length; i++) {
todoItems[i].addEventListener('click', handleClick);
}
function handleClick(e) {
const todoTag = e.target.closest('.todo-item');
const todoItem = todoTag.getElementsByClassName('todo')[0].innerText;
const clickeTodo = {
todoItem: todoItem
};
fetch('http://localhost:3000/', {
method: 'DELETE',
body: JSON.stringify(clickeTodo),
headers: { 'Content-type': 'application/json; charset=UTF-8' }
})
.then(response => response.json())
.catch(err => console.log(err));
}
Terminal output
Todo deleted from database.
[ RowDataPacket { todo: 'Clean' }, RowDataPacket { todo: 'Read' } ]
Todos read from database
I've learned that fetch won't send the browser to a new page if it gets a redirect response and this needs to be done on the client side instead. I've added window.location = response.url and it now works:
'use strict';
let todoItems = document.getElementsByClassName('todo-item');
for (let i = 0; i < todoItems.length; i++) {
todoItems[i].addEventListener('click', handleClick);
}
function handleClick(e) {
const todoTag = e.target.closest('.todo-item');
const todoItem = todoTag.getElementsByClassName('todo')[0].innerText;
const clickeTodo = {
todoItem: todoItem
};
fetch('http://localhost:3000/', {
method: 'DELETE',
body: JSON.stringify(clickeTodo),
headers: { 'Content-type': 'application/json; charset=UTF-8' }
})
.then(response => {
window.location = response.url;
response.json();
})
.catch(err => console.log(err));
}
whenever I click the delete button its works fine but I don't get the output like " deleted successfully " its shows .then undefined..
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
if (data.error) {
console.log(data.error);
} else {
preload();
}
});
};
here is the delete category API call
export const deleteCategory = (userId, categoryId , token) => {
fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
},
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
It should be like this. deleteCategory needs to send only promise. Later where ever you are resolving you have to use then.
export const deleteCategory = (userId, categoryId , token) => {
return fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
}
})
};
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
preload();
}).catch(err => {
console.log(err);
})
};
I'm following a MERN Stack course & I'm quite new, in that I'm keeping backend & frontend codes separately.
when I trying to POST a request through frontend I'm getting an error as below screenshot, but when I trying that same POST request through backend using Postman I'm able passing the value to my MongoDB database. I couldn't find any code error on this. I'm stacked here almost 3 weeks please help me on this.
I tried to call backend both ways as below but the result is same.
${API}/category/create/${userId}
and
${API}category/create/${userId}
please note I'm able to see my backend error message as well.
--------------------------------------------
screenshot :
--------------------------------------------
Backend API call file | Frontend
import { API } from "../../backend"
// category call
export const createCategory = (userId, token, category) => {
return fetch(`${API}/category/create/${userId}`, {
method:"POST",
headers:{
Accept: "application/json",
"Content-Type": "appliction/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify(category)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
// get all categories
export const getCategories = () => {
return fetch(`${API}/categories`, {
method: "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
// Product calls
export const createProduct = (userId, token, product) => {
return fetch(`${API}/product/create/${userId}`, {
method: "POST",
headers:{
Accept: "application/json",
Authorization: `Bearer ${token}`
},
body: product
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
// get all products
export const getProducts = () => {
return fetch(`${API}/products`, {
method: "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
// delete a product
// get a product
export const getProduct= () => {
return fetch(`${API}/product`)
}
// update a product
View file | Backend
import React, { useState } from "react";
import Base from "../core/Base";
import { Link } from "react-router-dom";
import { isAutheticated } from "../auth/helper";
import { createCategory } from "./helper/adminapicall";
const AddCategory = () => {
const [name, setName] = useState("");
const [error, setError] = useState(false);
const [success, setSuccess] = useState(false);
const { user, token } = isAutheticated();
const goBack = () => (
<div className="mt-3">
<Link className="btn btn-sm btn-success mb-3" to="/admin/dashboard">
Admin Home
</Link>
</div>
);
const handleChange = (event) => {
setError("");
setName(event.target.value);
};
const onSubmit = (event) => {
event.preventDefault();
setError("");
setSuccess(false);
//backend call fired
createCategory(user._id, token, {name}).then(data => {
if (data.error) {
setError(true);
} else {
setError("");
setSuccess(true);
}
})
};
const myCategoryFrom = () => (
<form>
<div className="form-group">
<p className="lead">Enter the category</p>
<input
type="text"
className="form-control my-3"
onChange={handleChange}
value={name}
required
autoFocus
placeholder="For Ex. Summer"
/>
<button onClick={onSubmit} className="btn btn-outline-info">
Create Category
</button>
</div>
</form>
);
return (
<Base
title="Create a category here"
description="Add a new category for new T-shirts"
className="container bg-info p-4 "
>
<div className="row bg-white rounded">
<div className="col-md-8 offset-md-2">
{myCategoryFrom()}
{goBack()}
</div>
</div>
</Base>
);
};
export default AddCategory;
Controller file [create category] | Backend
const Category = require('../models/category');
exports.getCategoryById = (req, res, next, id) => {
Category.findById(id).exec((err, cate) => {
if(err){
return res.status(400).json({
error: "Category is Not found in the Databse"
});
}
req.category = cate;
next();
});
};
exports.createCategory = (req, res) => {
const category = new Category(req.body);
category.save((err,category) => {
if(err){
return res.status(400).json({
error: "Not able to save Category in to the Database"
});
}
res.json({ category });
});
};
exports.getCategory = (req,res) => {
return res.json(req.category)
}
exports.getAllCategory = (req,res) => {
Category.find().exec((err,categories) => {
if(err){
return res.status(400).json({
error: "No Categories found"
})
}
res.json(categories);
});
};
exports.updateCategory = (req, res) => {
const category = req.category;
category.name = req.body.name;
category.save((err, updatedCategory) => {
if (err) {
return res.status(400).json({
error: "Failed to update category"
});
}
res.json(updatedCategory);
});
};
exports.removeCategory = (req, res) => {
const category = req.category;
category.remove((err, category) => {
if(err){
return res.satus(400).json({
error: "Failed to Delete this Category"
})
}
res.json({
message: "Successfull Deleted"
});
})
}
I would like to explain my problem of the day.
in the following code I map a table, and I post all of this in a database
everything works fine. the only problem and the format in which I receive it.
{
"id": 136,
"items": "[{\"title\":\"Campus (Pinte)\",\"quantity\":2}]",
}
I would rather recover it in another format than in arrays. here is my code:
postbackend = () => {
const newItems = this.props.items.map(item => {
const { title, quantity } = item;
return {
title,
quantity
};
});
const config = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({ ...this.state, items: newItems })
};
const url = entrypoint + "/alluserpls";
fetch(url, config)
.then(res => res.json())
.then(res => {
if (res.error) {
alert(res.error);
this.props.history.replace("/OrderSummaryPaymentFalseScreen"); // Your Error Page
} else {
alert(`film ajouté avec l'ID ${res}!`);
this.props.history.push("/OderSummaryScreen"); // Your Success Page
}
})
.catch(e => {
console.error(e);
this.props.history.replace("/OrderSummaryPaymentFalseScreen"); // Your Error Page
})
.finally(() =>
this.setState({
redirect: true
})
);
};
Do you have an idea of how to fix this?