Search code examples
reactjsreduxreact-reduxredux-thunk

Dispatch self action in a timeout


For some reason I cannot call the same function within a timeout.. if this wasn't an Action function it works just fine.. is this just not possible? I just want to make sure so I can move on or make a hack... thank you

export function initialize () {
  return function ( dispatch ) {

    if ( window.someAPIVar ) {
      console.log( 'done' );
    }
    else {
      console.log( 'looping' );
      //setTimeout( dispatch( initialize ), 250 );  // does not work
      //setTimeout( initialize, 250 );  // does not work
    }
  };
}

Solution

  • setTimeout( initialize, 250 );
    

    This will do nothing, since initialize is a function which returns another function. So after 250ms, setTimeout will invoke this function and you will not notice anything.

    setTimeout( dispatch( initialize ), 250 );
    

    The above will also not do anything useful. dispatch( initialize ) is executed immediately and the function it returns is what will be called after 250ms, which is not what you want. It looks like what you meant to do here is this:

    setTimeout( () => dispatch( initialize() ), 250 );
    

    You need to pass a function which calls dispatch, and dispatch needs to receive the value of an action creator, which will either be an object like { type: 'SOME_ACTION', payload: 1 } or a function like dispatch => dispatch({ type: 'SOME_ACTION', payload: 1 }).

    If this is a little confusing, read through the examples on the redux-thunk GitHub page at https://github.com/gaearon/redux-thunk.