Jerry Seigle
Jerry Seigle

Reputation: 457

React Native add to state array if value does not exist

I would like to know the best way to add a value to an array of the value does not exist in my state variable. The current code works but I a newbie and not sure if I am doing this correctly. This function is fired when a button is pressed

const App = () => {
  
  const [answered, setAnswered] = useState([])

  const handleConnectionAnswer = deviceId => {
    if (!anwsered.includes(deviceId)) {
      setAnswered(prev => [...prev, deviceId]);
    }
  };
}

Upvotes: 1

Views: 1168

Answers (1)

sachin007
sachin007

Reputation: 85

you're doing it right or you can simply do it like

if (!anwsered.includes(deviceId)) {
  setAnswered([...answered, deviceId]);
}

Upvotes: 3

Related Questions