Accessing the api from a component

I’m dabbling with Discourse themes but am not a web/Javascript developer. Looking at some third-party theme components I’ve got this question.

In discourse-header-submenus/javascripts/discourse/connectors/above-site-header/header-submenus.js, there’s this code:

export default {
  setupComponent() {
    // some code here
  },
};

There are no imports at the top of the file.

If I understand (strict) JavaScript correctly, the only context the code within setupComponent() will have access to are the attributes of the object it is evaluated on.

When I look at this context using console.log(this) within the setupComponent() function, it appears I have no access to the very handy api object.

That’s a pity!

Also, I wouldn’t know how to import it correctly since the official wrapper code for using api-functions is versioned and looks like this:

import { apiInitializer } from "discourse/lib/api";

export default apiInitializer("0.12.3", api => {
    // code that uses the api here
});

How could I access the api object from within setComponent()? Or am I missing something fundamental here?

1 Like

Got it, it’s done like this:

import { withPluginApi } from "discourse/lib/plugin-api";

export default {
    setupComponent() {
        withPluginApi("0.12.3", api => {
            console.log(api.getCurrentUser());
        });
    },
};
2 Likes

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.