Currently, I am using a side effect for a timer that sends an update action to the store every 0.1s:
const Timer = ({ update, score }) => {
useEffect(() => {
const interval = setInterval(() => {
update()
}, 100);
return () => clearInterval(interval);
})
return (<p>{score}</p>);
}
Where is the best place to initialise the timer in incrementAsynch()?
function incrementAsync() {
return (dispatch) => {
setTimeout(() => {
dispatch(update());
}, 100);
};
}
Should I keep it in useEffect?
const Timer = ({ update, score }) => {
useEffect(() => {
incrementAsync()
return () => clearInterval(interval);
})
return (<p>{score}</p>);
}
If so how do I stop it? And does this create multiple counters?
everytime you dispatch your incrementAsync a new interval starts but the old ones are not killed. so if you dispatch 3 times you will get 30 update actions per second.
Redux-Thunk is not very good for such cases. I would suggest that you try a middleware that is better suited for such problems.
The most important ones are - redux-saga - redux-observable
Both middlewares also have functionalities to cancel such timers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.