Home > Blockchain >  Why map() returns the value for all elements
Why map() returns the value for all elements

Time:05-22

There is an array of objects {id, value, active(true/false)}. When I click on an element, I set the active property to true and add this object to another array in state. When two elements appear in another array, then I do a check in useEffect, if the value of these elements are equal, then I do nothing, just clear array. If the values are not equal, then I want to change the active property to false for these elements in the first array. But for some reason, false changes for all elements, although there is a condition.

 const [memoryGameItems, setMemoryGameItems] = useState(data)
  const [currentItems, setCurrentItems] = useState([])

  const choosingItem = (id, value) => {
    setMemoryGameItems(memoryGameItems.map(item => {
      if (id === item.id) {
        return { ...item, active: true }
      }
      return item
    }))
    setCurrentItems([...currentItems, { id, value }])
  }

  useEffect(() => {
    if (currentItems.length === 2) {
      if (currentItems[0].value === currentItems[1].value) {
        setCurrentItems([])
      } else {
        setTimeout(() => {
          setMemoryGameItems(memoryGameItems.map(item => {
            if (item.id === currentItems[0].id || currentItems[1].id) {
              return { ...item, active: false }
            }
            return item
          }))
          setCurrentItems([])
        }, 500)
      }
    }
    // eslint-disable-next-line
  }, [currentItems])

CodePudding user response:

This item.id === currentItems[0].id || currentItems[1].id will always evaluate to true if currentItems[1].id is truthy.

You probably want something like item.id === currentItems[0].id || item.id === currentItems[1].id, I think.

  • Related