skip to Main Content

I have a problem I am trying to make a select form where the selection of an option suppose to toggle boolean value in an object from available: true to false. I think my solution is quite promising but I am getting error

import { useState } from 'react'


function App() {
  const [time, setTime] = useState("")
  const [availableSlots, setAvailableSlots] = useState([
    {value: '17:00', available: true},
    {value: '18:00', available: true},
    {value: '19:00', available: true},
    {value: '20:00', available: true},
    {value: '21:00', available: true},
    {value: '22:00', available: true}
  ])

  const toggleAv = () => {
    var selectedSlot = availableSlots.find((item) => {
        return item.value === time
    })
    setAvailableSlots(
        ...availableSlots,
        selectedSlot.available = false
    )
    console.log(availableSlots)
  }
  const handleSubmit = (e) => {
    e.preventDefault();
    toggleAv()
  }

  return (
    <>
      <form onSubmit={handleSubmit}>
        <select 
          name="time" 
          id="time" 
          value={time} 
          onChange={(e) => setTime(e.target.value)}
        >
          {availableSlots.map((item, key) => {
            return <option key={key} value={item.value}>{item.value}</option>
          })}

        </select>
        <input type="submit" value="Submit" />
      </form>
    </>
  )
}

export default App

Code works how it should, it just gives error when submitted. Should I use something else instead of find then? I don’t see any reason why I couldn’t use the .filter method like that…

2

Answers


  1. here is codesandbox repo with the solution. I just created a new array of slots with the updated "available" properties and then passed that new array to the setAvailableSlots() instead of spreading the existing availableSlots array.

    here is updated function

      const toggleAv = () => {
        const updatedSlots = availableSlots.map((slot) =>
          slot.value === time ? { ...slot, available: false } : slot
        );
        setAvailableSlots(updatedSlots);
        console.log(updatedSlots);
      };
    
    Login or Signup to reply.
  2. Use a for loop where it matches the time at index it will update the value. The code you are trying it is a spread operator. It will keep previous values and add one more item which is not a object kind. So it is not taking the .map() function.

    const toggleAv = () => {

    for (var i = 0; i < availableSlots.length; i++) {
      if (availableSlots[i].value === time) {
        availableSlots[i].available = false;
      }
    }
    

    };

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search