I have a form with some input with a default value and its hidden. I want to submit its value, together with other inputs to the database using an API, I have tried the following method, but it is not working. Kindly help.
const PostWidget = ({ post }) => {
const [loading, setLoading] = useState(false);
const [show, setShow] = useState(false);
const [commentInput, setComment] = useState({
post_id: '',
commentcontent: '',
});
const [errorlist, setError] = useState([]);
const handleInput = (e) => {
e.persist();
setComment({ ...commentInput, [e.target.name]: e.target.value });
}
const submitComment = (e) => {
e.preventDefault();
setLoading(true);
const data = {
post_id: commentInput.post_id,
commentcontent: commentInput.commentcontent,
};
axios.post(`/api/store-comment`, data).then((res) => {
if (res.data.status === 200) {
toast.success(res.data.message, "success");
setLoading(false);
}
else if (res.data.status === 422) {
toast.error("Your Comment is too Long", "", "error");
setError(res.data.errors);
setLoading(false);
}
});
}
return (
<div className="form-group boxed">
<div className="input-wrapper">
<form onSubmit={submitComment}>
<input defaultValue={post.postid} hidden />
<input type="text" name="commentcontent" className="form-control" onChange={handleInput} value={commentInput.commentcontent} placeholder="Write your Comment" />
<button type="submit" className="send-input">
{loading ? <><span className="spinner-border spinner-border-sm spinner-comment" role="status" aria-hidden="true"></span></> : <><i className="fi fi-rr-arrow-circle-right"></i></>}
</button>
</form>
</div>
);
}
export default PostWidget;
CodePudding user response:
I think your issue might be due to the fact that you're setting the initial state of post_id to an empty string and as far as I can tell, it never gets updated.
I don't think you even need to keep post_id in the commentInput state. Just remove it and change your data object to:
const data = {
post_id: post.post_id,
commentcontent: commentInput.commentcontent,
};
CodePudding user response:
Inside of your submitComment
you can use:
const postId = e.target["postId"].value
If you add following to your hidden input:
name="postId"
But in your instance you can just use post.postid
that you are getting from props instead of getting it from hidden input.