Home > Software design >  Is there a way to use && inside a ternary operator
Is there a way to use && inside a ternary operator

Time:11-13

Need to use multiple if condition in a ternary

const handleEditTask = (id) =>{ 
    return (
      tasks.map((x)=>{
        return x.id === id? setTitle(x.title): ;
      })
    )
  }

with true of that condition need to call two setState operatoion

using the ternary, just need to include the setNote() as well

CodePudding user response:

Please provide extra information on what you want to do. Do you simply want to add a && within the ternary operator? if yes, then you can easily add it before the question mark

const handleEditTask = (id) =>{ 
    return (
      tasks.map((x)=>{
        return x.id === id && yourConditionHere ? setTitle(x.title): "" ;
      })
    )
  }

However, if you intend to make set action for more than one setState/useState then you can create a parent function before the return statement and add your setState/useState inside of it, then call it in the ternary operator.

you can have a look at this example if its helps:

const [inputs, setInputs] = useState({
    firstName: "",
    lastName: ""
})

const handleClick = () => {
    setInputs({ ...inputs, firstName: "Andrea" })
    setInputs({ ...inputs, lastName: "Diotallevi" })
}

>> console.log(inputs)
>> { firstName: "", lastName: "Diotallevi" }

CodePudding user response:

just use if statement for simplicity, but if you really want to go for the ternary syntax. Use the , it'll look like this

   const handleEditTask = (id) =>{ 
        return (
          tasks.map((x)=>{
            return x.id === id? setTitle(x.title), setNote(<something-here>): ;
          })
        )
      }

CodePudding user response:

Use a filter first to remove the condition from map

const handleEditTask = (id) =>{
  return (
    tasks.filter(x=> x.id === id).map((x)=>{
      return setTitle(x.title).setNote() ;
    })
  )
}
  • Related