I'm using react-table and I'm trying to set selected rows on load. I've created some fakeData to test with which you can see in the fakeData const. I'm then trying to find a match between my table data and the fake data, and if a match exists update the setMySelectedRows
state.
In my code I'm getting the matches correctly (first console log), but state always returns blank (second console log after setting the state).
I'm not quite sure what I'm doing wrong here? Usually I would use an array and push my items in, but react-table expects this to be an object like below:
{"0": true, "9": true, "12": true}
Here is my code:
const [mySelectedRows, setMySelectedRows] = useState({});
const fakeData = [
{"collectibleId": "b94e5d49-35f0-4bdc-9e41-d5c484df5ae7", "quantity": 2},
{"collectibleId": "1def2f37-8043-4aa8-a490-b4024db216ff", "quantity": 2},
{"collectibleId": "ac5bc2af-f67d-46da-bac1-1b404a3dd6d1", "quantity": 2}
]
useEffect(() => {
let selectedObj = {}
collectibles && collectibles.map((collectibleRow, index) => {
var check = fakeData.find(c => c.collectibleId === collectibleRow.collectibleId);
const stringMyIndex = `${index}`
selectedObj = {[stringMyIndex]: true}
if (check){
console.log('found a match. ', selectedObj) // prints as expected
setMySelectedRows({...mySelectedRows, "0": true, "9": true})
console.log('selected rows state is: ', mySelectedRows) // prints blank object
}
})
}, [collectibles])