Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access latest state value in the same function that is used to set the state

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading