Home > Back-end >  Access latest state value in the same function that is used to set the state
Access latest state value in the same function that is used to set the state

Time:11-23

my state

const [selectedRows, setSelected] = useState([])

const handleRowClick = useCallback((id) => {
       if(selectedRows.includes[id]) {
           arr = selectedRows.filter((item) => item !== id) // <==Trying to access the state here
           setSelected((prev) => [arr])
       } else {
          setSelected((prev) => [id])
       }    
})

Everytime I try to access the selectedRows inside the handleRowClick function it just returns its default value,ie. an empty array

CodePudding user response:

You aren't using a dependency array for useCallback. You probably want this:

const handleRowClick = useCallback((id) => {
       if(selectedRows.includes[id]) {
           arr = selectedRows.filter((item) => item !== id) // <==Trying to access the state here
           setSelected((prev) => [...arr])
       } else {
          setSelected((prev) => [...id])
       }    
}, [selectedRows])

Note: notice that I'm destructuring the array so you get a new copy of the array and not an array with just one element.

  • Related