0

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])
alienbuild
  • 246
  • 2
  • 15
  • 3
    You won't be able to see the updated state immediately because React processes state updates asynchronously. So you need to use another `useEffect` hook to monitor the state and log when it updates: `useEffect(() => console.log(mySelectedRows), [mySelectedRows]);`. If your data is an array you should probably initialise your `useState` with an array rather than an object. – Andy Sep 16 '21 at 09:29
  • Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Ryan Le Sep 16 '21 at 09:33

0 Answers0