'How to realize select one but excluding the other in react IF condition?

So I wish to select "update" path inside a react component if one data 's name is found, then inside this "if" I have another "if(a window.confirm)", if user confirm, then execute to finish update. Within this component I have regular "add" new data path parallel with "update" which as mentioned contains two nested ifs conditions. I show you the code below. So far, seems none of the ifs works correctly. First if, after execution, keep running to "add" function, then the window.confirm, does not matter confirm or cancel, also does "add". Coudl you tell how should I adjust ?

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

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

        if (persons.find((person)=> person.name === newName)){
          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(persons.concat(returnPerson))
          setNewName('')
          setNewNumber('')
        console.log('added', nameObj)
        })
    }


Solution 1:[1]

add a return before the end of the close } of the first if, if you choose not to add an else,

If you don't add a return (to exit the function), it will continue to execute personService.create()


You currently have a return, but that's to return the promise, not to return the function.

For example

 if (persons.find((person)=> person.name === newName)){
     .......// do something

     return; // you need the return here 

    } else {
       //codes here will not execute if you don't add the above return
    }

    //codes here will continue to execute if you don't add the above return

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Someone Special