DEV Community

HarmonyOS
HarmonyOS

Posted on

How to store a function in LocalStorage?

Read the original article:How to store a function in LocalStorage?

Context

LocalStorage is a page-level UI state storage with certain type restrictions. LocalStorage supports types such as undefined, null, number, boolean, string, and Object, but does not support function type variables.

Description

How to store a function in LocalStorage?

Solution

LocalStorage does not support storing function-type variables. Encapsulate the function using a class to convert it into an Object, as LocalStorage supports storing Object types.

Code is as follows:

let storage: LocalStorage = new LocalStorage();

function openCommentsInput(title: string, hintMsg: string, clickSend: object) {
  storage.setOrCreate('title', title)
  storage.setOrCreate('hintMsg', hintMsg)
  storage.setOrCreate('clickSend', clickSend)
}

// Use a class to encapsulate a function.
class MyFunc {
  clickSend: Function = (content: string) => {}
}

// Function that needs to be saved to LocalStorage
function clickSend(ctx: string) {
  console.info(ctx)
}

@Entry(storage)
@Component
struct LocalStorageDemo {
  @LocalStorageLink('clickSend') myFunc: object = [] // Retrieve the clickSend object stored in LocalStorage

  build() {
    Column({ space: 20 }) {
      Button('Save data to storage')
        .onClick(() => {
          let myFunc: MyFunc = new MyFunc()
          myFunc.clickSend = clickSend // Encapsulate the function to be saved within a class object.
          openCommentsInput('title', 'hintMsg', myFunc) // Save the class object to LocalStorage
        })
      Button('Read data from storage')
        .onClick(() => {
          let tmp = this.myFunc as MyFunc // Convert the Object to MyFunc class
          tmp.clickSend('Successfully read data from storage.') // Call the clickSend function in MyFunc
        })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • LocalStorage does not support storing function-type variables.
  • Encapsulate the function using a class to convert it into an Object, as LocalStorage supports storing Object types.

Written by Mehmet Karaaslan

Top comments (0)