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.
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)