# Accessing the api from a component

**URL:** https://meta.discourse.org/t/accessing-the-api-from-a-component/271311
**Category:** Development
**Created:** [July 11, 2023, 10:41pm UTC](https://meta.discourse.org/t/accessing-the-api-from-a-component/271311 "2023-07-11T22:41:35Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![pipkin](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pipkin/32/134643_2.png) [@pipkin](https://meta.discourse.org/u/pipkin)
#### Post date: [July 11, 2023, 10:41pm UTC](https://meta.discourse.org/t/accessing-the-api-from-a-component/271311/1 "2023-07-11T22:41:35Z")

</div>

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](https://discourse-header-submenus), there’s this code:

```javascript
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:

```javascript
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?

---

<div class="post-metadata">

### Author: ![pipkin](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/pipkin/32/134643_2.png) [@pipkin](https://meta.discourse.org/u/pipkin)
#### Post date: [July 13, 2023, 7:26pm UTC](https://meta.discourse.org/t/accessing-the-api-from-a-component/271311/2 "2023-07-13T19:26:18Z")

</div>

Got it, it’s done like this:

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

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

```

---

<div class="post-metadata">

### Author: ![system](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/system/32/443519_2.png) [@system](https://meta.discourse.org/u/system)
#### Post date: [August 12, 2023, 7:26pm UTC](https://meta.discourse.org/t/accessing-the-api-from-a-component/271311/3 "2023-08-12T19:26:26Z")

</div>

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