Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does getState() from redux thunk changes the actual state

I'm retriving a slice of the state with getState() to filter some values from the state in an event handler (before dispatching an action and updating the store with the new state slice) But changing the results from getState seems to change the actual store.

Consider the following:

const filterInPlace = (array, predicate) => {
    let end = 0;

    for (let i = 0; i < array.length; i++) {
        const obj = array[i]

        if (predicate(obj)) {
            array[end++] = obj
        }
    }

    array.length = end
}
//some event handler
...
const forDeletion = new Set([...ids])
let currentState = getState().home.lists
filterInPlace(currentState, obj => !forDeletion.has(obj.rowid))
dispatch(handleSelectLists(ids)) //Leads to an action and reducer

Does getState() changes the store?

like image 223
docHoliday Avatar asked Jan 26 '23 14:01

docHoliday


1 Answers

getState() does not change the store, but it does return a reference to the store. Meaning when you say let currentState = getState().home.lists, currentState now points to your store. If you modify it it will change your store.

Obviously this is not what you want, so you need to make a copy.

Assuming lists is an array, this will do the trick.

let currentState = [...getState().home.lists]

like image 112
Galupuf Avatar answered Feb 02 '23 05:02

Galupuf