@forge/api: Cannot read properties of undefined (reading ‘fetch’)

Max Rozen

Max Rozen (@RozenMD) / May 02, 2021

The Problem

So you're working on a Custom UI Forge App, thinking it'd be cool to use the storage API.

You import storage like so: import { storage } from "@forge/api";, try to use it, similar to this:

// some-forge-app/static/hello-world/src/App.js
import { storage } from "@forge/api";
// more imports here...

const App () => {
    useEffect(()=>{
        const fetchData = async () => {
            await storage.set('test','someValue');
            const data = await storage.get('test);

            console.log('data: ', data);
        }

        fetchData();
    }, []);

    return <div>test</div>
}

You build your app, run forge deploy, and get this scary runtime error:

Forge fetch undefined error message

The Fix

You can't actually import from @forge/api directly in Custom UI apps.

Instead you need to define a resolver function (in Forge template apps, a basic one is provided in src/index.js), like so:

// src/index.js
import Resolver from '@forge/resolver';
import { storage } from '@forge/api';

const resolver = new Resolver();

resolver.define('get', async ({ payload, context }) => {
  const data = await storage.get(payload.key);
  console.log('data fetched: ', data);
  return data;
});

Then in your Custom UI app, you add an import for @forge/bridge's invoke function and call it in your component like so:

// some-forge-app/static/hello-world/src/App.js
import { invoke } from '@forge/bridge';
// ... the rest of your React component here
const data = await invoke('get', { key: saveKey });