Search code examples
reactjstypescriptreact-nativestorage

{"_h": 0, "_i": 0, "_j": null, "_k": null} on react native


Everytime I execute the getAllData() function it return {"_h": 0, "_i": 0, "_j": null, "_k": null} It look like encrypted I tried asking ChatGPT and It doesn't work TodoModal.ts

import AsyncStorage from '@react-native-async-storage/async-storage';

type TodoData = { title: string | undefined, items: string[] | undefined };

class TodoModal {
  private async saveData(key: string, data: any) {
    await AsyncStorage.setItem(key, JSON.stringify(data));
  }

  private async getData(key: string): Promise<TodoData> {
    const data = await AsyncStorage.getItem(key);
    if (data !== null) {
      return JSON.parse(data);
    } else {
      return { title: undefined, items: undefined };
    }
  }

  async addTitle(title: string) {
    console.log("Adding " + title)
    const data = await this.getData('todoData');
    const newData = { ...data, title };
    await this.saveData('todoData', newData);
    console.log(this.getAllData())
  }

  async addItem(item: string) {
    console.log("Adding " + item)
    const data = await this.getData('todoData');
    const newItems = data.items ? [...data.items, item] : [item];
    const newData = { ...data, items: newItems };
    await this.saveData('todoData', newData);
  }

  async getAllData(): Promise<TodoData[]> {
    const keys = await AsyncStorage.getAllKeys();
    const data = await AsyncStorage.multiGet(keys);

    const customData = data.map((item) => {
      const [key, value ] = item;
      if (key === 'title') {
        return { title: value!.toUpperCase(), items: undefined };
      } else if (key === 'items') {
        return { title: undefined, items: value!.split(',') };
      } else {
        return { title: undefined, items: undefined };
      }
    });

    return customData;
  }

  async deleteItem(item: string) {
    const data = await this.getData('todoData');
    if (data.items) {
      const newItems = data.items.filter((i) => i !== item);
      const newData = { ...data, items: newItems };
      await this.saveData('todoData', newData);
    }
  }

  async deleteTitle() {
    const data = await this.getData('todoData');
    const newData = { ...data, title: undefined, items: undefined };
    await this.saveData('todoData', newData);
  }
}

export default TodoModal;

Solution

  • Looks like you are logging a pending promise. Please try to await for the getAllData response:

    console.log(await this.getAllData())