React.js / Redux: setInterval and clearInterval in reducers

I am currently working on the FCC Game of Life , and I was able to figure out how to create the next state of the application (in stages).

So my next step is to figure out how to generate a new application state (generation) continuously. In this case, I am trying to implement setInterval and clearInterval inside my reducer .

I would like to be able to start / pause new generation generation (by switching state in state.start )

The fact that I have problems with its implementation is a problem with the area.

Here is part of my gearbox:

reducers / reducers _grid.js

export default function(state = initialState, action){ switch (action.type) { .... case START: let toggleStart = state.start === true ? false : true; if (state.start === true){ console.log('START THE GAME') const newGeneration = nextGeneration(action.payload,state) return Object.assign({}, state, {cells: newGeneration, start: toggleStart }) } else { console.log('PAUSE THE GAME') return Object.assign({}, state, {start: toggleStart }) } return state; } 

Essentially, the nextGeneration function displays the new state of the application (generation) and updates it using Object.assign

At first, I suggested that in the first if statement setInteveral and clearInterval in the second if statement, but obviously this would create a problem with the scope.

This part of the logic seems very trivial, but I've been stuck with this for a while.

+5
source share
1 answer

Do not do this in the gearbox. Gearboxes should be pure functions (which means no side effects). Instead, you can create a component that appears only when the game is running (a logical state that is set to true by the START actions and false by the STOP action). Then, the setInterval function is called in the componentDidMount componentDidMount with a function that dispatches the NEXT_GENERATION action. After that, another action is sent that adds the timer identifier to the repository. Then, in componentWillUnmount remove the interval based on the timer identifier.

+7
source

All Articles