Ben_Sven_Ten
Ben_Sven_Ten

Reputation: 579

Finding a specific object in state, removing it and replacing it in React

My current code finds an object in a state array, removes it and then adds a newValue in its place. I know using .splice() mutates the state directly which is not a recommended practice in React. What is the proper way to do what I am trying to do below?

      const found = clientServiceReferral.selectedTimeSlots.find(element => element.timeSlot === timeWithDate);

      if (found) {
        clientServiceReferral.selectedTimeSlots.splice(found, 1)
      }


      const newValue = {
        timeSlot: timeWithDate,
        value: value.value
      }

      setClientServiceReferral({
        ...clientServiceReferral,
        selectedTimeSlots: [...clientServiceReferral.selectedTimeSlots, newValue]
      })

Upvotes: 1

Views: 43

Answers (1)

Hyetigran
Hyetigran

Reputation: 1215

I would use map method, which returns a new array, to find and replace:

const updatedTimeSlots = clientServiceReferral.selectedTimeSlots.map((element) => {
    if(element.timeSlot === timeWithData){
      return {timeSlot: timeWithDate, value: value.value}
    } else {
      return element
    }
})
setClientServiceReferral({
    ...clientServiceReferral,
    selectedTimeSlots: updatedTimeSlots
})

Upvotes: 1

Related Questions