I want to make a Validator that validates uniqueness of items. If i want to create new stuff, I want to check if I have it in the database already first.
Code:
const [categList, setCategList] = useState([]);
const getItems = () => {
// Sending HTTP GET request
Axios.get(url).then((response) => {
const categories = [];
response.data.forEach((resCateg) => {
categories.push(resCateg.name + ", " + resCateg.description);
console.log(resCateg);
});
setCategList(categories);
});
};
And before i do:
function submit(e) {
e.preventDefault();
//reset form validation errors
resetFormValidationErrors();
Axios.post(url, {
// Sending HTTP POST request
name: data.name,
description: data.description,
}).then((res) => {
resetForm();
});
}
I want to check under "preventDefault" that my name is unique. Any help?
You just need to store names in your state and then you can check from that array if your name already exist or not.
Here's How to do it-
const [categList, setCategList] = useState([]);
const getItems = () => {
// Sending HTTP GET request
Axios.get(url).then((response) => {
const categoryNames = response.data.map(res => res.name)
setCategList(categoryNames);
});
};
Check while submitting -
function submit(e) {
e.preventDefault();
//reset form validation errors
resetFormValidationErrors();
// Checking here if `categList` already includes name
if(categList.includes(data.name.trim())) {
alert(`${data.name} is already taken, Please select any other name.`)
return
}
Axios.post(url, {
// Sending HTTP POST request
name: data.name,
description: data.description,
}).then((res) => {
resetForm();
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.