Skip to content

Commit

Permalink
Fix issues with reducer initial state causing collisions
Browse files Browse the repository at this point in the history
The initial state variable was being shared across all `<DndContext>` components in the same application, which was causing id collisions for both nested and sibling `<DndContext>` providers.
  • Loading branch information
Clauderic Demers committed Jan 12, 2021
1 parent 0d12e42 commit 2b54dab
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 18 deletions.
6 changes: 3 additions & 3 deletions packages/core/src/components/DndContext/DndContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,10 @@ import {
} from '@dnd-kit/utilities';

import {
Action,
Context,
DndContextDescriptor,
Action,
initialState,
getInitialState,
reducer,
} from '../../store';
import type {Coordinates, ViewRect, LayoutRect, Translate} from '../../types';
Expand Down Expand Up @@ -149,7 +149,7 @@ export const DndContext = memo(function DndContext({
modifiers,
...props
}: Props) {
const store = useReducer(reducer, initialState);
const store = useReducer(reducer, undefined, getInitialState);
const [state, dispatch] = store;
const {
draggable: {active, lastEvent, nodes: draggableNodes, translate},
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/store/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export {Action} from './actions';
export {Context} from './context';
export {reducer, initialState} from './reducer';
export {reducer, getInitialState} from './reducer';
export type {
Data,
DraggableElement,
Expand Down
33 changes: 19 additions & 14 deletions packages/core/src/store/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,26 +2,28 @@ import {omit} from '../utilities';
import {Action, Actions} from './actions';
import type {State} from './types';

export const initialState: State = {
draggable: {
active: null,
initialCoordinates: {x: 0, y: 0},
lastEvent: null,
nodes: {},
translate: {x: 0, y: 0},
},
droppable: {
containers: {},
},
};
export function getInitialState(): State {
return {
draggable: {
active: null,
initialCoordinates: {x: 0, y: 0},
lastEvent: null,
nodes: {},
translate: {x: 0, y: 0},
},
droppable: {
containers: {},
},
};
}

export function reducer(state: State, action: Actions): State {
switch (action.type) {
case Action.DragStart:
return {
...state,
draggable: {
...initialState.draggable,
...state.draggable,
initialCoordinates: action.initialCoordinates,
active: action.active,
lastEvent: Action.DragStart,
Expand All @@ -47,7 +49,10 @@ export function reducer(state: State, action: Actions): State {
return {
...state,
draggable: {
...initialState.draggable,
...state.draggable,
active: null,
initialCoordinates: {x: 0, y: 0},
translate: {x: 0, y: 0},
lastEvent: action.type,
},
};
Expand Down

0 comments on commit 2b54dab

Please sign in to comment.