Accessing the api from a component

AI-generated summary

Accessing the API from a Component

The discussion revolves around accessing the api object from within a component’s setupComponent() function in a Discourse theme. pipkin initially found that the api object was not accessible within the function and was unsure how to import it correctly. However, pipkin later discovered the solution, which involves importing withPluginApi from discourse/lib/plugin-api and using it to access the api object within the setupComponent() function.

Example code:

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

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

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?

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());
        });
    },
};