I have made a web app where you can upload images via an image url. Here is the link: https://meme-gallery-web-app.netlify.app/
The problem is if I press the submit button where the form is empty, it still posts an empty image data to database.
My question is how can I activate the button only when there's a proper image ur? Only when a proper image url is submitted in the form, then the button will activate and I can submit it. Here is the code where I handle the form request.
import { FormControl, Input, Button } from "@chakra-ui/react";
import axios from "axios";
import React from "react";
import { baseUrl } from "../config";
class SubmitLink extends React.Component {
constructor(props) {
super(props);
this.state = {
url: "",
};
}
onInputChange = (event) => {
this.setState({
url: event.target.value,
});
};
// where I make post request.
onClick = () => {
axios
.post(`${baseUrl}/submitlink`, {
url: this.state.url,
})
.then((response) => {
console.log(response);
this.props.onSuccessfulUpload();
this.setState({
url: "",
});
})
.catch(function (error) {
console.log(error);
});
};
render() {
return (
<FormControl>
<Input
type='url'
value={this.state.url}
onChange={this.onInputChange}
width={{
base: "70%",
md: "55%",
xl: "60%",
}}
ml={{
base: "5%",
md: "5%",
xl: "4%",
}}
/>
<Button
ml={2}
mb={1}
colorScheme='teal'
type='submit'
onClick={this.onClick}
size='md'
>
Submit
</Button>
</FormControl>
);
}
}
export default SubmitLink;
here's the API where I handle the post request
// post api for saving images from URL
const imageModel = require("../models/models.js");
//ignore the date variables. haven't properly implemented it.
var date = new Date();
var currentDate = date.toLocaleDateString();
const submitLink = async (req, res) => {
let saveImageFromUrl = new imageModel();
saveImageFromUrl.img.data = req.body.url;
saveImageFromUrl.postedAt = currentDate;
await saveImageFromUrl.save(function (err, result) {
if (err) return console.error(err);
else {
res.sendStatus(202);
}
});
};
module.exports = submitLink;