Issues with storing and getting data from Forge Storage API

Am trying to store and retrieve stored data via Forge storage API but it throws error below

There was an error invoking the function - Cannot read property 'get' of undefined
TypeError: Cannot read property 'get' of undefined
    at fetchStoredData (index.js:12821:95)
    at index.js:12828:95
    at processInitialValueAndThrow (index.js:12340:54)
    at Object.exports.useAction (index.js:12355:9)
    at exports.useState (index.js:29490:24)
    at Object.App [as type] (index.js:12828:76)
    at index.js:29288:36
    at asyncMap (index.js:29223:30)
    at index.js:29244:35
    at asyncMap (index.js:29223:30)

Below is the code:

import api, { route} from "@forge/api";
import { storage } from '@forge/api';
import ForgeUI, { render, Fragment, Macro, Text,useProductContext, useState } from "@forge/ui";
//import { storage } from '@forge/api';

const fetchStoredData = async (contentId) => {

  // store data here
	storage.set('myfirst_key', {first_name: 'Ann', last_name: 'Rachael', age: '21' });
	storage.set('myfirst_key', {first_name: 'Frank', last_name: 'James', age: '19' });
	//await storage.get('myfirst_key');
	// query stored data
	 const data = await (
              await api.asUser().storage.get('myfirst_key')
return data.results;



const App = () => {
const context = useProductContext();
  const [reco] = useState(async () => await fetchStoredData(context.contentId));

  console.log(`Number of Records: ${reco.length}`);	

  return (
      <Text>Display Stored Data Here</Text>

 {reco.length ?, i) => (
          <div key={i}>
            <div >

<b>First Name:</b>  {v.first_name}<br />
<b>Last Name:</b>  {v.last_name}<br />

            </div><br />
        )) : <div >Organisation Data has not been Added by Admin Yet...</div>}


export const run = render(
    app={<App />}
1 Like


await storage.set('myfirst_key', {first_name: 'Ann', last_name: 'Rachael', age: '21' });
await storage.set('myfirst_key', {first_name: 'Frank', last_name: 'James', age: '19' });

Otherwise ‘myfirst_key’ is not being set before storage.get is called.

I think there are a few problems here.

  • You are setting the same storage key twice
  • You need an await on storage operations
  • You don’t access storage via api.asUser()
  • Not sure what .json() is for. If you save an object, it will read as an object so there is no need to try parse it.

See updated code below:

const fetchStoredData = async (contentId) => {
    await storage.set('myfirst_key', {first_name: 'Ann', last_name: 'Rachael', age: '21' });
    await storage.set('mysecond_key', {first_name: 'Frank', last_name: 'James', age: '19' });
    const data = await storage.get('myfirst_key');
    return data;