Fix flight position update performance.

dispatch is expensive when called in a loop because each call
re-renders. Doing more work per dispatch causes fewer renders.

https://redux.js.org/style-guide/style-guide#avoid-dispatching-many-actions-sequentially
This commit is contained in:
Dan Albert 2022-03-05 00:42:22 -08:00
parent 05fbdae54c
commit 35df036eb8
2 changed files with 12 additions and 10 deletions

View File

@ -11,7 +11,7 @@ import {
selectFlight, selectFlight,
unregisterFlight, unregisterFlight,
updateFlight, updateFlight,
updateFlightPosition, updateFlightPositions,
} from "./flightsSlice"; } from "./flightsSlice";
import { import {
addFrontLine, addFrontLine,
@ -47,11 +47,9 @@ export const handleStreamedEvents = (
dispatch: AppDispatch, dispatch: AppDispatch,
events: GameUpdateEvents events: GameUpdateEvents
) => { ) => {
for (const [id, position] of Object.entries( dispatch(
events.updated_flight_positions updateFlightPositions(Object.entries(events.updated_flight_positions))
)) { );
dispatch(updateFlightPosition([id, position]));
}
for (const combat of events.new_combats) { for (const combat of events.new_combats) {
dispatch(newCombat(combat)); dispatch(newCombat(combat));

View File

@ -42,9 +42,13 @@ export const flightsSlice = createSlice({
const id = action.payload; const id = action.payload;
state.selected = state.flights[id]; state.selected = state.flights[id];
}, },
updateFlightPosition: (state, action: PayloadAction<[string, LatLng]>) => { updateFlightPositions: (
const [id, position] = action.payload; state,
action: PayloadAction<[string, LatLng][]>
) => {
for (const [id, position] of action.payload) {
state.flights[id].position = position; state.flights[id].position = position;
}
}, },
}, },
}); });
@ -56,7 +60,7 @@ export const {
updateFlight, updateFlight,
deselectFlight, deselectFlight,
selectFlight, selectFlight,
updateFlightPosition, updateFlightPositions,
} = flightsSlice.actions; } = flightsSlice.actions;
export const selectFlights = (state: RootState) => state.flights; export const selectFlights = (state: RootState) => state.flights;