Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting undefined when using import() to dynamically import an instantiated class object

I am getting undefined when I try to read any properties on my instantiated class object that I get from using import(). Not sure what else to try besides this below…

Code in one of my components:

import { IModel } from '@/core/types'

// code omitted for brevity

const [model, setModel] = useState<IModel | null>(null)

useEffect(() => {
    ;(async () => {
        const data: IModel = await import(`../../core/models/${instance.component.name}Model.ts`)
        setModel(_ => data)
    })()
}, [instance.component.name])

Here instance.component.name would have a value of ToDoList located at <project-root>/src/core/models/ToDoListModel.ts. The code doing the import is located at <project-root>/src/components/MyComponent/MyComponent.tsx.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My model:

import { IModel } from '@/core/types'

class ToDoListModel implements IModel {
    public name: string
    public isDropContainer: boolean
    public requiredProps: string[]

    private _dropBlacklist: string[]

    constructor() {
        this.name = 'ToDoList'
        this.isDropContainer = false
        this.requiredProps = []
        this._dropBlacklist = ['Test']
    }

    public isDragAllowed = (): boolean => {
        return true
    }

    public isDropAllowed = (component: IModel): boolean => {
        return this.isDropContainer && !this._dropBlacklist.includes(component.name)
    }
}

const model = new ToDoListModel()

export default model

When I try to console.log(model?.name) I get undefined. No errors in the console which tells me the import is resolving the module just fine.

>Solution :

You wanted to assign default to the variable, not the entire module

const data: IModel = (await import(`../../core/models/${instance.component.name}Model.ts`)).default
setModel(_ => data)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading