I just started learning redux< redux-toolkit and ran into the problem that my stat from the "Pastime" reducer always returns the initial value, although it works correctly in another functional component.
The reducer
import { createSlice } from '@reduxjs/toolkit'
type TInitialState = {
value: number;
}
const initialState: TInitialState = {
value: 10,
}
const passTimerSlice = createSlice({
name: 'passTimer',
initialState,
reducers: {
setDefault: state => {
state.value = 12
},
addSeccond: state => {
state.value -= 1
}
},
})
export const { addSeccond, setDefault } = passTimerSlice.actions
export default passTimerSlice.reducer
useEffect(() => {
dispatch(slices.passTimer.setDefault())
passTimerId = setInterval(() => {
console.log('passTimer', passTimer)
if (passTimer <= 0) {
clearInterval(passTimerId)
return
}
dispatch(slices.passTimer.removeSeccond())
}, 1000)
return () => {
clearInterval(passTimerId) // Clear interval on component unmount
}
}, [passState])
I will be glad of any hint
I reread the documentation, but I didn’t find what my mistake was.
2
Answers
I solved this problem by putting the tracking of the timerState value change in a separate useEffect
Every time your
passState
changes, you dispatch aslices.passTimer.setDefault()
action, so I would assume that you either want an empty dependency array there, or to remove that dispatch.