How to submit a hidden input with default value to API

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;

>Solution :

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,
};

Leave a Reply