how to updata any data in database after sucessfully showing console? - reactjs

As you can in the react (clint-side) code , i am trying increase/decrese of Quantity in database and UI.
in this code i am sucessfully show quantity in console . but i don't show it my UI and database . Now what should i do ?
Server side (react)
const { register, handleSubmit } = useForm();
const onSubmit = (data, event) => {
const url = https://nameless-dusk 43671.herokuapp.com/products/${productsId}
fetch(url, {
method: "PUT",
headers: {
'content-type': "application/json"
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(result => {
console.log(result)
event.target.reset()
}
)
}
update item on clint side
app.put('/products/:id', async (req, res) => {
const id = req.params.id;
const updateUser = req.body;
const filter = { _id: ObjectId(id) }
const options = { upsert: true };
const updateDoc = {
$set: {
name: updateUser.name,
email: updateUser.email,
}
}
const result = await
ProductCollection.updateOne(filter, updateDoc,
options)
res.send(result)
})

Related

MongoDB / ReactJS Patch handler / findOneAndUpdate not working

in the following code, I'm attempting to update the Checkpoints field for one of my objects within the projects collection. UpdatedCheckpoints is working correctly, so I believe the first block of code works. But the change isn't logging to the database so it doesn't persist. What's going wrong?
const onApprovedSubmit = useCallback(
async (e) => {
e.preventDefault();
let updatedCheckpoints = props.project.Checkpoints;
updatedCheckpoints[props.checkpointIndex].checkpointSubmitted = true;
console.log('here');
try {
let projectId = props.project._id;
await fetcher('/api/projects', {
method: 'PATCH',
headers: { 'Content-type': 'application/json' },
body: JSON.stringify({ Checkpoints: updatedCheckpoints }),
id: projectId,
});
toast.success('Your checkpoint has been updated');
} catch (e) {
toast.error(e.message);
}
},
[props],
);
handler.patch(async (req, res) => {
const db = await getMongoDb();
const project = await updateProjectById(db, req.id, req.body);
res.json({ project });
});
export async function updateProjectById(db, id, data) {
return db
.collection('projects')
.findOneAndUpdate(
{ _id: new ObjectId(id) },
{
$set: data,
},
{ returnDocument: 'after' },
)
.then(({ value }) => value);
}

dataLoaded state only changed after page reloaded

I'm doing an API call to get some data. then I keep a useState called dataLoaded. on a successful API call I make the dataLoaded=true. but to see it changed I have to reload the page.
following is my code.
const [dataLoaded, setDataLoaded] = useState(false)
useEffect(() =>{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/movie/`+ path.eventId + `/venue/`+ path.venue +`/showtime`;
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
const fetchData = async () => {
try {
const response = await fetch(url, requestOptions());
const json = await response.json();
// console.log(json);
// console.log(json.data.venueDateShowtime)
setShowTimes(json.data.dateShowtimes[0].showtimes[0]);
console.log(json.data.dateShowtimes[0].date)
setShowdate(json.data.dateShowtimes[0].date);
setDataLoaded(true);
console.log(dataLoaded)
console.log(showTimes.showtimeId)
console.log(showdate)
if(dataLoaded){
getSeatsArrangement();
}
console.log('jjjj')
}
catch (error) {
console.log("error",error);
}
};
fetchData();
},[]);
const getSeatsArrangement = async () => {
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
console.log(showTimes.showtimeId)
console.log(showdate)
try{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/seat?venueId=` + path.venue + `&movieId=`+ path.eventId +`&showtimeId=1011&movieDate=2022-10-11`;
const response = await fetch(url,requestOptions());
const json = await response.json();
console.log(json)
setReservedSeats(json.data.reservedSeats.reservedSeat)
setNonReservedSeats(json.data.reservedSeats.nonReservedSeats)
console.log(reservedSeats)
console.log(nonReservedSeats)
} catch(error) {
console.log("error",error);
}
}
Console logs when page loads
What is the aim of the code? fetchData is performed once after page loading (because of using ,[] at the end of useeffect.
And a remark: If you log your state right after setting it, the previous value will be shown! you should define another useeffect with your state as dependency (for each state) and log your state in there.
useEffect(() => {
console.log(dataLoaded)
if(dataLoaded){
getSeatsArrangement();
}
console.log('jjjj')
}, [dataLoaded]);
useEffect(() => {
console.log(showTimes.showtimeId)
}, [showTimes]);
useEffect(() => {
console.log(showdate)
}, [showdate]);
useEffect(() =>{
const url = `${process.env.REACT_APP_DEV_BASE_URL}/v1/movie/`+ path.eventId + `/venue/`+ path.venue +`/showtime`;
const requestOptions = (token) => {
return ({
method: 'GET',
headers: { 'Content-Type': 'application/json', 'client_token': '4ece-9e89-1b6d4d2cbb61' }
})
};
const fetchData = async () => {
try {
const response = await fetch(url, requestOptions());
const json = await response.json();
// console.log(json);
// console.log(json.data.venueDateShowtime)
setShowTimes(json.data.dateShowtimes[0].showtimes[0]);
console.log(json.data.dateShowtimes[0].date)
setShowdate(json.data.dateShowtimes[0].date);
setDataLoaded(true);
}
catch (error) {
console.log("error",error);
}
};
fetchData();
},[]);

Unexpected token 2 in JSON at position 0?

express
this is the error " at JSON.parse ()
at createStrictSyntaxError (E:\programming_hero\phone-store-server\node_modules\body-parser\lib\types\json.js:160:10)
at parse (E:\programming_hero\phone-store-server\node_modules\body-parser\lib\types\json.js:83:15)
at E:\programming_hero\phone-store-server\node_modules\body-parser\lib\read.js:128:18
at AsyncResource.runInAsyncScope (node:async_hooks:202:9)
at invokeCallback (E:\programming_hero\phone-store-server\node_modules\raw-body\index.js:231:16)
at done (E:\programming_hero\phone-store-server\node_modules\raw-body\index.js:220:7)
at IncomingMessage.onEnd (E:\programming_hero\phone-store-server\node_modules\raw-body\index.js:280:7)
at IncomingMessage.emit (node:events:539:35)
at endReadableNT (node:internal/streams/readable:1345:12)"
app.put('/quantity/:id', async (req, res) => {
const id = req.params.id;
const quantity = req.body;
const updateQuantity = JSON.parse(quantity);
const filter = { _id: ObjectId(id) };
const options = { upsert: true };
const updateDoc = {
$set: {
quantity: updateQuantity.quantity
}
};
const result = await phoneDB.updateOne(filter, updateDoc, options);
res.send(result);
})
react
and client site error is put URL is 404 and (bad Request)
const increase = () => {
setCount(count + 1)
const totalQuantity = count + number;
const url = `http://localhost:5000/quantity/${id}`
fetch(url, {
method: 'PUT',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(totalQuantity)
})
.then(res => res.json())
.then(result => {
console.log(result);
})
}

Update the likes array in a post in the frontend

I have a PUT route in the backend for liking posts, it adds the users id to the likes array in the post. This works fine when tested on Postman (by providing the post in the body) and the likes array is updated. However, when the icon is clicked in the frontend, I want the likes array to update but I'm not sure how to update the state for the post. result is showing the response in the frontend with a 200 status code but that's as far as I'm getting.
How can I update the likes array in the frontend?
Post.js
const Post = (props) => {
const [post, setPost] = useState({});
const [error, setError] = useState(false);
const id = props.match.params.id;
const loadSinglePost = (id) => {
read(id).then((data) => {
if (error) {
console.log(data.error);
setError(data.error);
} else {
setPost(data);
console.log(data);
}
});
};
useEffect(() => {
loadSinglePost(id);
}, [props]);
const like = (id) => {
const {user: { _id }, token} = isAuthenticated();
fetch(`${API}/like/${_id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
id: id,
}),
})
.then(result => { console.log(result)})
.catch((err) => {
console.log(err);
});
};
return (
<div>
<Navbar />
<div>
<h3>{post && post.title}</h3>
<p>
{post && post.author ? post.author.name : ""}
</p>
<p>{post && post.body}</p>
<h5>{post && post.likes && post.likes.length} likes</h5>
<img
onClick={() => {
like(id);
}}
alt="..."
/>
</div>
</div>
);
};
export default Post;
controllers/post.js
exports.like = (req, res) => {
Post.findByIdAndUpdate(req.body._id, {
$push: {likes: req.profile._id}
}, {new: true}).exec((err, result) => {
if (err) {
return res.status(422).json({error: err})
} else {
return res.json(result)
}
})
}
exports.readById = (req, res) => {
const id = req.params.id
Post.findById(id)
.then(post => res.json(post))
.catch(err => res.status(400).json('Error: ' + err));
}
You can update likes in post in then callback like this:
const like = (id) => {
const {user: { _id }, token} = isAuthenticated();
fetch(`${API}/like/${_id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
id: id,
}),
})
.then(result => {
// here update post likes
let updatedPost = {...post}; //to make copy of post
updatedPost.likes = [...updatedPost.likes, id]; //add new id to updatedPost' likes array
setPost(updatedPost); //update post
console.log(result)
})
.catch((err) => {
console.log(err);
});
};
Also from front-end you're sending id key in body:
body: JSON.stringify({
id: id, // here
})
And at back end you're expecting _id
Post.findByIdAndUpdate(req.body._id, { // here
$push: {likes: req.profile._id}
}

Post, split props ReactJs

I would like to explain my problem of the day.
this is the part of the code that works
here I recovered 2 data "title" and "quantity" here it works very well
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
}));
so i tried this ,and I would like to separate "title" and "quantity".
example like this
const newItems = this.props.items.map((item) => {
const { title } = item;
return {
title,
};
});
const newQuantity = this.props.items.map((item) => {
const { quantity } = item;
return {
quantity,
};
});
const config = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ ...this.state, items: newItems, quantityforproduct: newQuantity,
};
but it doesn't work
Do you have an idea of how to fix this? Neff

Resources