Keep getter function in sync with an object’s current state in React/TypeScript

WHAT I HAVE

I have a Parent class and a Child class.

export class Parent {
    properties: { x: any };
    child: Child;
    constructor() {
        this.properties = {
            x: 1
        }
        this.child = new Child(this.getX);
    }
    getX = () => {
        return this.properties.x;
    }
}

class Child {
    parent_getX:()=>string
    constructor(parent_getX:()=>string){
        this.parent_getX = parent_getX;
    }
}

The Parent class has:

  • a field called properties which stores an int value called x.
  • a function called getX() which simply pulls the value of x from within the properties object.
  • a field called child which holds a reference to a Child object.

The Child class only receives a reference to the Parent‘s getX() function.

WHAT I WANT

My goal is to be able to update the value of x and that everytime I call child.parent_getX() or parent.getX() I get the latest value of x.

WHAT I’M SEEING

I have a React component called Example that takes a Parent object with a an x value of 1 as initial state.

Whenever I increment this value using setState(...) the value of x is incremented but for some reason, parent.getX() and parent.child.parent_getX() always keeps returning the initial value of x. What can I do to keep the function in sync with the parent object?

export const Example = () => {

    const [parent, setParent] = useState(new Parent());

    const incrementX = ()=>{
        let newParent = { ...parent, properties: { ...parent.properties, x: parent.properties.x + 1 } }
        setParent(newParent);
    }

    return (<>
        <p>
            Parent.getX() = {parent.getX()}
            <br/>
            Parent.child.parent_getX() = {parent.child.parent_getX()}
        </p>
        <button onClick={incrementX}>
            Increment
        </button>
    </>);
}