How to set TextFieldValue from the previously stored value using storage api

Hi,
I’m struggling with creaing a AdminPage which contains a TextBox and Submit button which will accept the secret key. I want to show the existing value on the page load and new value upon submit. Can you please help me here

import ForgeUI, { render, AdminPage, Form,Fragment,Text, TextField, useState,Button, useProductContext, useEffect } from '@forge/ui';
//import ForgeUI, { render, Fragment, Text, IssuePanel,Button, ButtonSet, useProductContext, useState, Component, useEffect} from "@forge/ui";

import { storage, fetch } from '@forge/api';

const cancel = () => {};
const actionButtons = [
    <Button text="Cancel" onClick={cancel} />,
];

/*
useEffect(()=> {
    getOpenAIKeyfromStorage().then((data) =>{
        setOpenAIKeyValue(data);
    });
},[]);
*/
const App = () => {
    

     const { platformContext } = useProductContext();
     const [formState, setFormState] = useState(undefined);
     const [openAIKeyValue, setOpenAIKeyValue] = useState("");

     const getOpenAIKeyfromStorage = async()=>{
        const data = await storage.get('openAIkey');
        console.log("getopenAIKeyfromStorage ="+data);
           setOpenAIKeyValue(dataFromStorage);

        return data || " ";
    
    };
     console.log(" ************* Starting ****************")
    let dataFromStorage=getOpenAIKeyfromStorage();
   // setOpenAIKeyValue(dataFromStorage);
     console.log("In App from Storage APIKey  dataFromStorage ="+JSON.stringify(dataFromStorage));

    const handleOpenAIKeySubmit = async (formState) => {
    
        let openAIkey=formState["openAIKey"];
        console.log(" In handleOpenAIKeySubmit : openAIKey "+openAIkey);

        // Store the text in storage
        await storage.set("openAIkey", formState["openAIKey"]);
        setFormState(openAIkey);
        setOpenAIKeyValue(openAIkey);

        const data = await storage.get('openAIkey');
        console.log("data from Storage ="+data);
        return data;
    };

    const handleOpenAIKeyChange = async (newValue) => {
        setFormState(newValue);
        setOpenAIKeyValue(newValue);

        try{
            await storage.set("openAIkey",newValue);
        }catch(error){
            console.log("ERROR while setting to storage in handleOpenAIKeyChange ="+error);

        }    
    };

    return (

        <Fragment>
            <Form onSubmit={handleOpenAIKeySubmit} actionButtons={actionButtons}>
                 <TextField name="openAIKey" label="Enter OpenAI Secret Key"  value={openAIKeyValue}  />
            </Form>
        {formState && <Text>{formState["openAIKey"]}</Text>}
      </Fragment> 

    /*  
      <form>
        <TextField label="Enter OpenAI Secret Key" name="openAIKey" />
        <Button
          text="Submit"
          onClick={async (event) => {
            event.preventDefault();
            const text = document.querySelector('input[name="openAIKey"]').value;
            await handleTextSubmit(text);
          }}
        />
      </form>
      */
    );

};

export const adminPage = render(
    <AdminPage>
        <App />
    </AdminPage>
);
modules:
  jira:adminPage:
    - key: my-test-app1-hello-world-admin-page
      function: main
      title: My Admin Page
  function:
    - key: main
      handler: index.adminPage
app:
  id: ari:cloud:ecosystem::app/7b115702-0b1b-473e-b667-7fd2d11710fb
permissions:
  scopes:
    - storage:app
    - read:jira-user
    - write:jira-work
    - write:issue:jira

Below is the logs

INFO    2023-09-18T16:53:40.364Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc  ************* Starting ****************
INFO    2023-09-18T16:53:40.370Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc In App from Storage APIKey  dataFromStorage ={}
INFO    2023-09-18T16:53:40.371Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc  In handleOpenAIKeySubmit : openAIKey Chandra Open AI test
INFO    2023-09-18T16:53:40.518Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc getopenAIKeyfromStorage =TestOpenAIKey
INFO    2023-09-18T16:53:40.602Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc data from Storage =Chandra Open AI test
INFO    2023-09-18T16:53:40.603Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc  ************* Starting ****************
INFO    2023-09-18T16:53:40.604Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc In App from Storage APIKey  dataFromStorage ={}
INFO    2023-09-18T16:53:40.604Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc  ************* Starting ****************
INFO    2023-09-18T16:53:40.605Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc In App from Storage APIKey  dataFromStorage ={}
INFO    2023-09-18T16:53:40.605Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc  ************* Starting ****************
INFO    2023-09-18T16:53:40.607Z 2f9abd58-6132-4415-8fba-b2cb7e56a6dc In App from Storage APIKey  dataFromStorage ={}

May i know where i’m doing error

Hi @ChandraSekhar1 ,

You can use the useAction hook from @forge/ui to loads the storage value and pass this into the default value of your useState hook for the openAIkey. In addition, change your TextField by replacing your value prop to a defaultValue prop.

Here is the full refactored code:

import ForgeUI, { render, AdminPage, Form,Fragment,Text, TextField, useState,Button, useProductContext, useAction } from '@forge/ui';
//import ForgeUI, { render, Fragment, Text, IssuePanel,Button, ButtonSet, useProductContext, useState, Component, useEffect} from "@forge/ui";

import { storage, fetch } from '@forge/api';

const cancel = () => {};
const actionButtons = [
    <Button text="Cancel" onClick={cancel} />,
];

/*
useEffect(()=> {
    getOpenAIKeyfromStorage().then((data) =>{
        setOpenAIKeyValue(data);
    });
},[]);
*/
const App = () => {
    

     const { platformContext } = useProductContext();
     const [formState, setFormState] = useState(undefined);

     const getOpenAIKeyfromStorage = async()=>{
        const data = await storage.get('openAIkey');
        console.log("getopenAIKeyfromStorage ="+data);
        // setOpenAIKeyValue(dataFromStorage);
        return data || " ";
    
    };

    const [originalAIKey] = useAction(value => value, async () => await getOpenAIKeyfromStorage());
     const [openAIKeyValue, setOpenAIKeyValue] = useState(originalAIKey);

     console.log(" ************* Starting ****************")
    let dataFromStorage=getOpenAIKeyfromStorage();
   // setOpenAIKeyValue(dataFromStorage);
     console.log("In App from Storage APIKey  dataFromStorage ="+JSON.stringify(dataFromStorage));

    const handleOpenAIKeySubmit = async (formState) => {
    
        let openAIkey=formState["openAIKey"];
        console.log(" In handleOpenAIKeySubmit : openAIKey "+openAIkey);

        // Store the text in storage
        await storage.set("openAIkey", formState["openAIKey"]);
        setFormState(openAIkey);
        setOpenAIKeyValue(openAIkey);

        const data = await storage.get('openAIkey');
        console.log("data from Storage ="+data);
        return data;
    };

    const handleOpenAIKeyChange = async (newValue) => {
        setFormState(newValue);
        setOpenAIKeyValue(newValue);

        try{
            await storage.set("openAIkey",newValue);
        }catch(error){
            console.log("ERROR while setting to storage in handleOpenAIKeyChange ="+error);

        }    
    };

    return (

        <Fragment>
            <Form onSubmit={handleOpenAIKeySubmit} actionButtons={actionButtons}>
                 <TextField name="openAIKey" label="Enter OpenAI Secret Key"  defaultValue={openAIKeyValue}  />
            </Form>
        {formState && <Text>{formState["openAIKey"]}</Text>}
      </Fragment> 

    /*  
      <form>
        <TextField label="Enter OpenAI Secret Key" name="openAIKey" />
        <Button
          text="Submit"
          onClick={async (event) => {
            event.preventDefault();
            const text = document.querySelector('input[name="openAIKey"]').value;
            await handleTextSubmit(text);
          }}
        />
      </form>
      */
    );

};

export const adminPage = render(
    <AdminPage>
        <App />
    </AdminPage>
);

Regards,
Dugald

1 Like