Search code examples
javascriptreactjsreduxredux-thunk

Redux does not call actions properly


In my React Native app I have redux actions to load and play a video. Whenever a user plays a video, the following will be executed:

this.props.dispatch(loadVideo(true, mediaID))

And the corresponding actions:

export const loadVideo = (isLoading, videoId) => async dispatch => {

   dispatch({
       type: LOAD_MEDIA,
       payload: isLoading
   })

   if(videoId){
      dispatch(playVideo(videoId))
   }
}


export const playVideo = (videoId) => async dispatch => {
    let p = await obtainMediaSource(videoId);

    dispatch({
       type: PLAY_MEDIA,
       payload: p
   })
   dispatch(loadVideo(false))
}

The problem is that somehow loadVideo action is waiting for playVideo action to finish executing before updating the state. However, I wish that loadVideo immediately updates the state to notify the app that a video is about to be loaded. What am I doing wrong here? Isn't this a good way to call actions (one calls the other)?


Solution

  • This is a good scenario to make use of .then() rather than await.

    This way, you'll have a non-blocking function and capitalize on the callback to asynchronously dispatch PLAY_MEDIA once the media source has been fully obtained.

    Here's an untested refactored code:

    export const setLoading = (isLoading) => dispatch => {
       dispatch({
           type: LOAD_MEDIA,
           payload: isLoading
       })
    }
    
    export const loadVideo = (videoId) => dispatch => {
    
       if (!videoId) return;
    
       setLoading(true);
    
       // non-blocking
       obtainMediaSource(videoId)
         .then((p) => {
           dispatch({
             type: PLAY_MEDIA,
             payload: p
           })
           setLoading(false);
         });
    }