Fetch API does not work for me

Hello,

according to this site it should be possible to use api.fetch(url, options ) for external calls.

I’m building a custom ui app and I need get a file. I tried it int App.JS from in static content and index.js but both run into the same error: Uncaught TypeError: Cannot read property ‘fetch’ of undefined
at Object.t.wrapFetchApiMethods (index.js:8)

Thanks
Marco

1 Like

Hi @hansemarco,

At the moment in a custom UI app, you need to make external calls via a resolver function. See custom ui resolver. Here is where you’ll use @forge/api and make your fetch call.

You’ll invoke the resolver via the @forge/bridge which will receive whatever data your resolver function returns.

Hope that helps!

3 Likes

Thanks, now it works.

2 Likes

For those who are trying to mock @forge/api for the testing purpose, you need to ignore or replace the module per se to avoid letting the module refer to the global object. In Jest, you can configure the replacement like as below:

export default {
  // ...
  "moduleNameMapper": {
    "@forge/api": "<rootDir>/test/mock/api.ts"
  },
  // ...
}
4 Likes

Regarding my comment above, making a long story short, with @forge/api:2.0.1 or later, I found it’s better to mock the global.api object rather than the entire module.

// forgeApi returns your mock object
Object.defineProperty(global, 'api', {value: forgeApi()})

For jest, the configuration would be something like below instead:

  setupFilesAfterEnv: [
    './test/mock/forgeApi.ts',
  ],
2 Likes