I am working on a Mernstack application, everything in my application is working well except the input field that doesn't clear after submission.
my Component
const [comments, setCommentData] = useState([]);
const onSubmit = useCallback(
(e) => {
e && e.preventDefault();
axios
.post(
"http://localhost:9000/events/" +
props.match.params.id +
"/eventcomment",
{ name: name, description: eventDescription }
)
.then(function (response) {
console.log("response", response.data.eventcomments);
onPageLoad();
})
.catch(function (error) {
console.log(error);
});
},
[props.match.params.id, name, eventDescription]
);
I tried doing this but it didn't work.
setCommentData("");
The initial state is [], so you should restore it to the same initial content:
setCommentData([]);
Related
enter image description here
this is the error ,the data is being shared across from step one enter code hereform up to step five
enter code here
//register user after submit details
const handleSubmit = async (event) => {
event.preventDefault();
try {
const { user } = props
//update image selected to the user
const formData = new FormData();
formData.append('image', files[0]);
const updatedData = {
...user,
image: files[0].name
};
//register user
await axios.post(`${BASE_API_URL}/api/auth/register`, { ...user, ...updatedData });
Swal.fire('Awesome!', "You're successfully registered!", 'success').then(
(result) => {
if (result.isConfirmed || result.isDismissed) {
props.resetUser();
navigate('/user/login');
}
}
);
} catch (error) {
console.log(error)
if (error.response) {
Swal.fire({
icon: 'error',
title: 'Oops...',
text: error.response.data
});
console.log('error', error.response.data);
}
}
};
Check the network tab in the browser to see wich data you are sending in the body. If the email is not present in the request, then try to log the props.user
I am using axios for the request of my own api, everything works correctly except the DELETE request, I looked for information about the error but I have not found the solution. when I send the request to the server I get this error: "xhr.js:210 DELETE http://localhost:3000/posts/62575cb61cb27c6417732193 403 (Forbidden)".
I put this line of code in Package.Json to avoid problems with CORS:
"proxy": "http://localhost:8080/api"
This would be my api, for the operation I pass the post id by url and the user id:
(I tried it in postman and it works without any problem)
router.delete("/:id", async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (post.userId === req.body.userId) {
await post.deleteOne();
res.status(200).json("the post has been deleted");
} else {
res.status(403).json("you can delete only your post");
}
} catch (err) {
res.status(500).json(err);
}
});
and this is where I consume my api:
const Post = ({ date, _id,userId, description }) => {
const handleDelete = async () => {
try {
await axios.delete('posts/' + _id, { userId: currentUser._id })
} catch (error) {
console.log(error)
}
}
return(
<div onClick={handleDelete }>
//component content
</div>
)
}
export default Post
I solved it, sending a data object to my api (inside that object I put the user id):
const handleDelete = async () => {
try {
await axios.delete('/posts/' + _id, {
data: {
userId: currentUser._id
}
}
)
} catch (error) {
console.log(error)
}
}
I recently created a simple MERN application that is supposed to use a form to send data to the backend using Redux to maintain state management. I'm new to Redux (as you will see in my code) and I believe I must have messed up the dispatching.
Below are the functions in my Form component:
const [landlordData, setLandlordData] = useState({name: '', type: '', rating: '', details: ''});
const dispatch = useDispatch();
const handleSubmit = (e) => {
e.preventDefault();
console.log(landlordData);
dispatch(createLandlord(landlordData));
}
Which console log the data from the form normally. When I submit though the new entry in the MongoDB only includes the time created and the UUID of the entry due to the Schema of the database:
import mongoose from 'mongoose';
const landlordSchema = mongoose.Schema({
name: String,
type: String,
rating: Number,
details: String,
createdAt: {
type: Date,
default: new Date()
}
});
var landlordDetails = mongoose.model('Landlords', landlordSchema);
export default landlordDetails;
To provide more context on the backend operations here is the controller script I made:
import landlordDetails from '../models/landlords.js';
export const getLandlords = async (req, res) => {
try {
const getDetails = await landlordDetails.find();
console.log(getDetails);
res.status(200).json(getDetails);
} catch (error) {
res.status(404).json({ message: error.message });
}
}
export const createLandlords = async (req, res) => {
const details = req.body;
const newLandlord = new landlordDetails(details);
try {
await newLandlord.save();
res.status(201).json(newLandlord);
console.log("New landlord added!");
} catch (error) {
res.status(409).json({ message: error.message })
}
}
Please let me know if any more information is needed or if I am completely oblivious to something obvious. Thank you.
EDIT: To provide more context, here are my api calls and my action script:
API:
import axios from 'axios';
const url = 'http://localhost:5000/landlords';
export const fetchLandlords = () => axios.get(url);
export const createLandlord = (landlordData) => axios.post(url, landlordData);
Actions JS file:
import * as api from '../api/index.js';
//Action creators
export const getLandlords = () => async (dispatch) => {
try {
const { data } = await api.fetchLandlords();
dispatch({ type: 'FETCH_ALL', payload: data });
} catch (error) {
console.log(error.message);
}
};
export const createLandlord = (landlord) => async (dispatch) => {
try {
const { data } = await api.createLandlord(landlord);
dispatch({ type: 'CREATE', payload: data });
} catch (error){
console.log(error);
}
};
When I click the submit button, a new database entry is made with the createdAt field but nothing else.
I am building an ecommerce with mern stack
When I make request from react to node and it fails it show the status code with error on the page.
is there a way to prevent this from happening
enter image description here
React code
export const createCategories = async(name, token) => {
return await axios.post(
`${process.env.REACT_APP_SERVER_APP_URL}/api/category`,
name,
{
headers: {
'x-header-token' : token
}
}
)
}
const handleSubmit = async(e) => {
e.preventDefault();
setLoading(true)
try{
createCategories(category, localStorage.getItem('token'))
.then(res => {
console.log(res)
setLoading(false)
setCompleted(true)
setCreateCategory(res.data)
});
}catch(err){
setError(true)
setErrorMsg({
"msg": err.response.data
})
}
}
nodejs code
try{
const {name} = req.body;
const category = await new Category({ name, slug: slugify(name)}).save();
res.json({'msg': "Category Created"})
}catch(err){
res.status(400).send("Create Category Failed...")
console.log(err)
}
you should use catch block
createCategories(name,token).then(res => {
// if success in response
}).catch(error => {
// if error in response
})
I have made a react form and want to make a post request to webhook.site with the form data. If I receive a 200 status code then I want to send the form data to a backend express server for further operation.
I am using axios to make the POST request.
This is the axios snippet from my react form:
import React, { Fragment, useState } from "react";
import axios from "axios";
const Form = () => {
const [candidate, setCandidate] = useState({
fullName: "",
phoneNumber: 0,
email: "",
gitProfile: "",
linkToResume: "",
designation: "",
interest: "",
});
const onChange = e =>
setCandidate({ ...candidate, [e.target.name]: e.target.value });
const onSubmit = e => {
e.preventDefault();
axios
.post("http://localhost:5000/", {
candidate,
})
.then(res => {
console.log(res, candidate);
});
};
Currently i am directly sending data to the backend. I have individually checked posting to both the webhook.site and backend, the code is working fine. But I want to do it simultaneously. If I get a 200 status code after posting to webhook.site, then only I want to send the form data to backend.
axios
.post("http://localhost:5000/", {
candidate,
})
.then(res => {
console.log(res, candidate);
// Write your another post request here because if your first request return 200 statusCode it will execute this function otherwise it will go catch function
}).catch(error => {
// if your first request failed then it execute this function. Here you can get error message.
console.log(error);
});
Check if first POST return status 200, then call next request.
axios
.post("http://localhost:5000/", {
candidate,
})
.then(res => {
console.log(res, candidate);
if (res.status === 200) {
axios.post('/url', {data})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
}).catch(function (error) {
console.log(error);
});