I have an element that I create through a visitor pattern:
public Create(): void {
...
globalThis.pinConfiguration.parts.push({type: this.element.localName, id: this.element.id, top: 0 , left: 0 });
const arr1: string[] = [this.elementID+":A", "pin:10"];
const arr2: string[] = [this.elementID+":C", "pin:GND"];
globalThis.pinConfiguration.connections.push(arr1, arr2);
...
Drag(this.element);
...
}
The Drag method looks like this
export function Drag(element: HTMLElement) {
const simulation = document.getElementById('simulation--simulationArea');
element.onmousedown = (e) => {
simulation!.addEventListener('mousemove', handler);
dragStart(e);
}
element.onmouseup = (e) => {
simulation!.removeEventListener('mousemove', handler);
simulation?.dispatchEvent(new Event('change'));
dragEnd(e);
}
let xdiff: number = 0;
let ydiff: number = 0;
let isDragging: boolean = false;
const dragStart = (e: any) => {
xdiff = (e.screenX - element.getBoundingClientRect().left);
ydiff = (e.screenY - element.getBoundingClientRect().top);
isDragging = true;
};
const dragging = (e: any) => {
if (isDragging) {
var left = e.screenX - xdiff - simulation!.getBoundingClientRect().left;
var top = e.screenY - ydiff - simulation!.getBoundingClientRect().top;
element.style.top = (top + "px").toString();
element.style.left = (left + "px").toString();
globalThis.pinConfiguration.parts.find(part => part.id === element.id)!.top = top;
globalThis.pinConfiguration.parts.find(part => part.id === element.id)!.left = left;
}
};
const handler = (e: any) => {
dragging(e);
};
const dragEnd = (e: any) => {
isDragging = false;
};
}
The problem is that the entire created object seems to remember the initial globalThis.pinConfiguration state and when I later change the global variable elsewhere (connect to different pins for instance) and then try to drag the created component, the global values are back to the ones with which the element was created.
// This works
function handleConnectionsChange(newValue: string) {
try {
globalThis.pinConfiguration = JSON.parse(newValue);
setEditorContext(newValue);
console.log('handleConnectionsChange');
console.log(globalThis.pinConfiguration);
}
catch (err) {
console.error(err);
}
}
Is there a way to use a pointers/references in react? It seems to me that the global variable gets just duplicated to a different place in the memory during element creation and that this is the root of the entire problem.
Has anyone ever encountered and solved this? I'm not a web developer, perhaps the problem will be glaringly obvious to you. Thank you.
Storing state in React can be done with useState:
const [pinConfiguration, setPinConfiguration] = useState({
parts: [],
connections: [],
});
Use setPinConfiguration whenever you want to update the global state and pinConfiguration whenever you want to access it.