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?
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With