skip to Main Content

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


  1. Chosen as BEST ANSWER

    I solved this problem by putting the tracking of the timerState value change in a separate useEffect

        useEffect(() => {
        console.log(timerState)
        if (timerState <= 0) {
            clearInterval(timerId)
            console.log('time end')
        }
    }, [timerState])
    

  2. Every time your passState changes, you dispatch a slices.passTimer.setDefault() action, so I would assume that you either want an empty dependency array there, or to remove that dispatch.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search