Questions & Answers

Can function components in Deepkit be asynchronous?

Template
50 up-votes
Warning: The answer is generated by an artificial intelligence. It might not be correct.
To adjust rating, open the thread in Discord and click on the up/down vote button.

Yes, function components in Deepkit can be asynchronous. This is a difference from other template engines like React. For example:

async function MyAsyncComponent() {
    // Perform asynchronous operations here
    // ...

    return <div>Async Component</div>;
}

To pass dependencies to function components in Deepkit, you can declare them as additional parameters in the component function. For example:

class Database {
    users: any[] = [{ username: 'Peter' }];
}

function UserList(props: {}, database: Database) {
    return <div>{database.users.length}</div>;
}

class MyPage {
    @http.GET('list')
    list() {
        return <UserList/>
    }
}

new App({
    controllers: [MyPage],
    providers: [Database],
    imports: [new FrameworkModule()]
}).run();

In the above example, the Database dependency is passed to the UserList function component as an additional parameter.

Class components in Deepkit can be used as an alternative way to write components. They have the advantage of being instantiated in the Dependency Injection container, giving them access to all services registered in the container. This allows class components to directly access data sources like databases. Here's an example:

class UserList {
    constructor(
        protected props: {},
        protected children: any,
        protected database: SQLiteDatabase) {
    }

    async render() {
        const users = await this.database.query(User).find();

        return <div class="users">
            {users.map((user) => <UserDetail user={user}/>)}
        </div>;
    }
}

class MyPage {
    @http.GET('')
    listUsers() {
        return <UserList/>;
    }
}

In the above example, the UserList class component is instantiated in the Dependency Injection container and has access to the SQLiteDatabase service.

In the constructor of a class component in Deepkit, the first arguments are reserved. props can be defined arbitrarily, children is always "any", and then optional dependencies follow, which you can choose arbitrarily. Since class components are instantiated in the Dependency Injection container, you have access to all your services.

class MyComponent {
    constructor(
        protected props: { prop1: string },
        protected children: any,
        protected dependency1: Dependency1,
        protected dependency2: Dependency2) {
    }
}

In the above example, prop1 is passed as a prop to the component, and dependency1 and dependency2 are dependencies injected from the container.

Please let me know if there's anything else I can help with!