'How can I keep my useSelector() variable from a redux store updated after each dispatch?(Redux Toolkit)
So I'm using React Native with Redux Toolkit and I'm facing this issue where once I dispatch and decrement a store value, the variable inside the component that grabs the state from the store does not update until the next render. It would be nice to know what the current value is at all times. I was thinking something like useEffect(), but I'm not sure how I would set that up. Any ideas would be appreciated.
Here is the component where the dispatch happens(inside handlePress function) and also where the redux state variable "exercises" I grab is found.
const LoggingButton = ({ disabled, maxReps, setIndex, exerciseIndex }) => {
const dispatch = useDispatch()
if (!maxReps)
maxReps = 5
const [count, setCount] = useState(maxReps)
const [active, setActive] = useState(false)
const { exercises } = useSelector((state) => state.workout);
const handlePress = () => {
if (!active)
setActive(true)
else {
dispatch(decrement({exerciseIndex:exerciseIndex,setIndex:setIndex}))
}
console.log("pressed",exercises[exerciseIndex].sets)
}
if (disabled)
return (
<Button
disabled round style={styles.disabledState}
iconSource={() => (<FontAwesomeIcon icon={faTimes} color={'#282c34'} size={30} />)}
/>)
else
return (
<Button
label={(count != 0) ? count : '0'} round
style={(active) ? styles.loggingState : styles.initialState} labelStyle={(active) ? styles.loggingLabel : styles.initialLabel}
onPress={handlePress}
/>)
}
Here is the workout state if it helps:
const currentWorkoutSlice = createSlice({
name: "currentWorkout",
initialState: {
id: "A",
exercises: [
],
timeStarted: '',
},
reducers: {
setWorkout(state, action) {
state.id = action.payload
},
setCurrentExercises(state, action) {
state.exercises = action.payload
},
setTimeStarted(state, action) {
state.timeStarted = action.payload
},
decrement(state, action) {
let newList = state.exercises.map(e=>e)
const {exerciseIndex,setIndex} = action.payload
newList[exerciseIndex].sets[setIndex] -=1
}
}
})
Solution 1:[1]
The whole point of useSelector
is to update your component as soon as that state changes so you always render the most up-to-date state contents.
"Until next render" is an incredibly short amount of time here and will often even happen synchonically. You should not really care about that.
Also, due to scoping those are two very different variables that just randomly have the same name - there is no way one could update the other.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |