How to add a checking feature(for duplication) before adding new data to server react?

Viewed 16

in a situation I need to update a person's number attribute, before update I need to generate a window confirm if that person's name is find already in db.json. How do you think I can do this ? To be more specific:

<form onSubmit={addName}> needs to do things depends on what I have in db.json. if the name exists, then addName does update, if not addName adds new input. the current code always add half duplicate data input i.e., different id, number, but same name. And when deleting data gives map not a function

const addName = (event) => {
      
        event.preventDefault()

        const nameObj = {
          name: newName,
          number: newNumber,
          id: nanoid()
    
        }

        if (persons.find((person)=> person.name === newName)){
          //myArray.find(x => x.id === '45').foo;
          const id = persons.find(person=>person.name===newName).id
          const changedPerson = {...nameObj, number: nameObj.number}
          if (window.confirm(`${newName} already there`)) {
            personService
            .update(id, changedPerson)
            .then(returnPerson=>{
              setPersons(persons.map(person => person.id === id ? person : returnPerson))
              setNewName('')
              setNewNumber('')
              return 
            })
          }
        }
        personService
        .create(nameObj)
        .then(returnPerson=>{
          setPersons(returnPerson)
          setNewName('')
          setNewNumber('')
        })
    }

1 Answers

You can check it in two common ways before submit:

  • Using a debounce function on every keyPress of the input to check if the name is already there. The debounce will prevent the function to only do the check when a specific time is reached (simulating when the user finishes typing). You can create your own function or use libs such as lodash debounce.

  • Using the useRef React hook to get the input value before the form submit.

  const inputName = useRef(null);
  const onButtonClick = () => {
    inputName.current.value(); 
    // this represents the current value of the input
  };

Check about the hook usage here.

Related