'What are my options to deal with this stale closure in React besides using ref
I'm using the library React Datasheet Grid, the main component has a property called OnActiveCellChange, to which i'm passing my custom function:
const [selectedCell, setSelectedCell] = useState([])
...
function handleCellSelection({ cell }) {
if(cell) {
const {row, col} = cell;
const newData = data[row][col];
if(!newData.unpickable) {
console.log(selectedCell); // prints empty array
setSelectedCell(selectedCell => [...selectedCell, newData.value]);
}
}
}
...
<DataSheetGrid
className={'overwriteDisabledStyles'}
value={data}
onChange={setData}
columns={columns}
onActiveCellChange={handleCellSelection}
headerRowHeight={false}
gutterColumn={false}
lockRows
/>
The problem is that I wish to make some checks with the state variable "selectedCell", while I managed to update the state from with the functional form, I can't access the the state variable. I managed to use the variable using "useRef".
I want to know if I can tackle the problem in any other way.
EDIT:
Trying to clarify my question:
What I want is to, inside the handleCellSelection function, make some checks before inserting the newData using the setSelectedCell. Like searching the selectedCell array for existing values:
const valueAlreadyExists = selectedCell.some((existingCell) => {
return existingCell === newData.value
});
Yet, when the handleCellSelection function is called, the value of selectedCell is always an empty array. It should be the values that are being inserted in the array. I know there are values there because when I console.log outside the handleCellSelection they appear correctly.
So, I managed to access them inside the handleCellSelection using useRef() but what I am searching for is another option to solve this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
