0

Hello stackoverflow I have a problem for react native, I am developing my functionality which allows me to like a post but when I push my id on my array my console is empty. to see my table I have to click a second time on another post so that my first id is displayed in my table.

here is my code

 const [liked, setLiked] = useState([])

    const arr = []

    const Like = (item) => {
        if (liked.indexOf(item) === -1) {
            const newArr = [...liked]
            newArr.push(item)
            setLiked(newArr)
            console.log(liked)
            console.log("ADD ID")
        }
    }
    


    const removelike = (item) => {
        if (liked.indexOf(item) >= 0) {
        console.log(liked.indexOf(item))
        const DeleteID = liked
        DeleteID.splice(item, 1)
        setLiked(DeleteID)
        console.log("Delete ID")
        }
    }
  • Splice requires a starting index and a delete count (not the element). Try simplifying your `removeLike` body to `setLiked(liked.filter(l => l !== item));` – windowsill Jan 11 '21 at 18:36
  • I correct my code using indexof to retrieve my index thank you –  Jan 11 '21 at 18:49

1 Answers1

0

The useState that is been used is actually asynchronous. So console logging liked after setLike won't be showing the updated value. To check the value you need to console the value in an useEffect

useEffect(()=> {
    console.log('liked',liked);    
}, [liked])

you can perform additional operations within the useEffect as it would only get called once the value of liked has changed

Erick
  • 1,098
  • 10
  • 21