Home > Software design >  How do I check if the name is already taken in database? React Axios
How do I check if the name is already taken in database? React Axios

Time:11-19

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?

CodePudding user response:

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();
    });
}
  • Related