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

View File

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