0

console always returns "true" meaning except first button click

        import React, {useState} from 'react'
        function App() {
            let [itemState, setLike] = React.useState( [
                      { id:1, likeIt:false, }
                    ])
                    function addToWish(id){
                      setLike( itemState.map(item=> {
                        if(item.id === id){
                          item.likeIt = !item.likeIt 
                        }
                        return itemState
                      })) 
                    }
                     console.log(itemState)
                   return(<button onClick={()=> addToWish()}></button>);}
Yaya
  • 4,402
  • 4
  • 19
  • 43
Bogdan9817
  • 25
  • 1
  • 4

1 Answers1

1

The correct way to update the state in your case would be to use a functional update and also in the callback passed to map you should return the item.

function addToWish(id) {
  setLike((prevState) =>
    prevState.map((item) =>
      item.id === id ? { ...item, likeIt: !item.likeIt } : item
    )
  );
}
Ramesh Reddy
  • 10,159
  • 3
  • 17
  • 32
  • tried to edit due to you're reccomendation suggestion, but problem is staying, just now it returns only false – Bogdan9817 Jan 25 '21 at 17:34
  • @Bogdan9817 I think you're logging at the wrong place. state is updated asynchronously. Check [this](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately?rq=1). – Ramesh Reddy Jan 25 '21 at 17:41