Search code examples
javascriptredux

How do I update a Redux store value on a timer?


I'm playing around with a bit more of reudx and I'm trying to display a value which works. The initial state is set to 0.

My goal is to increment this value by 1 every second. To accomplish this I did something like this:

  setInterval(() => {
    dispatch(Increment());
  }, 1000);

It's not really working the way I want it to, even though it increments, it does it at an extremely fast pace.

Also, another question. Inside my reducer I would in theory like to make expressions like this:

Increment: (state) => {
      state.value + 1;
    },

But when I do this redux throws the following error:

Expected an assignment or function call and instead saw an expression

Is it not possible to make such expressions inside a redux reducer?


Solution

  • Firstly your function here does not have a return statement

    Increment: (state) => {
      state.value + 1;
    },
    

    try to change it to

    Increment: (state) => {
      return state.value + 1;
    },
    

    or use parenthesis () to instead of using {()}

    Increment: (state) => (
      state.value + 1;
    ),
    

    And also don't forget that reducers are pure functions .............................................................

    your reducer should be something like this

    const initialState = { count: 0 };
    export default function reducer(state = initialState, action) {
      switch(action.type) {
         case 'INCREMENT':  
           return {         
            count: state.count + 1       
          };     
         case 'DECREMENT':       
           return {         
           count: state.count - 1       
          };     
         default:       
           return state;   
      } 
    }
    

    you should then have an action that you dispatch with a type like this

    dispatch({type:'INCREMENT'})
    

    since you already have an action helper function

    it goes like this

    function increment() {
       return {
       type: "INCREMENT"
      } 
    };
    
    function decrement() {
       return {
       type: "DECREMENT"
      } 
    };
    

    then you can do this

     setInterval(() => {
        dispatch(increment());
      }, 1000);