Bladeren bron

fix: treat state as previous state in effect builders

Fela Maslen 4 jaren geleden
bovenliggende
commit
790c1e17ce
2 gewijzigde bestanden met toevoegingen van 14 en 10 verwijderingen
  1. 4 5
      gmus-web/src/effects/effects.spec.ts
  2. 10 5
      gmus-web/src/effects/effects.ts

+ 4 - 5
gmus-web/src/effects/effects.spec.ts

@@ -13,9 +13,8 @@ import {
   songInfoFetched,
   stateSet,
 } from '../actions';
-import { globalReducer, GlobalState, initialState } from '../reducer';
+import { GlobalState, initialState } from '../reducer';
 import { Song } from '../types';
-import { MusicPlayer } from '../types/state';
 import { globalEffects } from './effects';
 
 describe(globalEffects.name, () => {
@@ -28,7 +27,7 @@ describe(globalEffects.name, () => {
     it('should create a remote state set action', () => {
       expect.assertions(1);
 
-      const localPlayer: MusicPlayer = {
+      const localPlayer = {
         songId: 123,
         playing: false,
         currentTime: 83,
@@ -41,11 +40,11 @@ describe(globalEffects.name, () => {
 
       const action = stateSet(localPlayer);
 
-      const result = globalEffects(globalReducer(state, action), action);
+      const result = globalEffects(state, action);
 
       expect(result).toStrictEqual<ActionStateSetRemote>({
         type: ActionTypeRemote.StateSet,
-        payload: { ...localPlayer, seekTime: 83 },
+        payload: { ...state.player, ...localPlayer },
       });
     });
   });

+ 10 - 5
gmus-web/src/effects/effects.ts

@@ -1,13 +1,14 @@
 import {
   ActionQueueOrdered,
   ActionQueuePushed,
+  ActionStateSetLocal,
   ActionTypeLocal,
   ActionTypeRemote,
   LocalAction,
   RemoteAction,
 } from '../actions';
 import { GlobalState } from '../reducer/types';
-import { isMaster } from '../selectors';
+import { getNextPlayerStateFromAction, isMaster } from '../selectors';
 
 const reverseInArray = <T>(array: T[], index: number): T[] => [
   ...array.slice(0, Math.max(0, index)),
@@ -39,20 +40,24 @@ function pushToQueue(state: GlobalState, action: ActionQueuePushed): RemoteActio
   };
 }
 
-function sendStateUpdateToServer(state: GlobalState): RemoteAction | null {
-  if (!state.player.master) {
+function sendStateUpdateToServer(
+  state: GlobalState,
+  action: ActionStateSetLocal,
+): RemoteAction | null {
+  const nextPlayer = getNextPlayerStateFromAction(state.player, action.payload);
+  if (!state.player.master && !nextPlayer?.master) {
     return null;
   }
   return {
     type: ActionTypeRemote.StateSet,
-    payload: state.player,
+    payload: nextPlayer,
   };
 }
 
 export function globalEffects(state: GlobalState, action: LocalAction): RemoteAction | null {
   switch (action.type) {
     case ActionTypeLocal.StateSet:
-      return sendStateUpdateToServer(state);
+      return sendStateUpdateToServer(state, action);
 
     case ActionTypeLocal.Seeked:
       if (!state.player.master) {