简体   繁体   中英

AsyncStorage singleton in React Native

I want to make a singleton that will collect all the data that I need around the app. Maybe this approach is wrong, then please correct me.

Right now my Singleton class has simple code:

import { AsyncStorage } from 'react-native'

export default class DataManager {
    static myInstance = null

    stringsArray = null

    static instance() {
        if (DataManager.myInstance == null) {
            DataManager.myInstance = new DataManager();
        }

        return this.myInstance;
    }

    async getStringsArray() {
      if (this.stringsArray == null) {
        let strings = await AsyncStorage.getItem('stringsArray')
        this.stringsArray = JSON.parse(strings)
      }
        return this.stringsArray
    }

    async setStringsArray(strings) {
        this.stringsArray = strings;
        await AsyncStorage.setItem('stringsArray', JSON.stringify(strings))
    }
}

This is how I want to call getters and setters:

DataManager.instance().setStringsArray(["abc", "def"])

let stringsArray = DataManager.instance().getStringsArray()

Unfortunately if I set something I can not receive it later. I will be glad for some help in that case

如果您正在寻找在各种组件之间共享数据或通过App共享数据的方法,请尝试redux https://blog.cloudboost.io/getting-started-with-react-native-and-redux-6cd4addeb29

I think you want to store some parameters on your AsyncStorage but you do not want to every time import it and use it to save your parameter on phone storage. The common way for react-native apps is using redux-persist library. By using this library you are able to save every parameter which is in your redux store. You can read more about it here https://github.com/rt2zz/redux-persist . You can put every parameter that you want in redux-persist whitelist and it would be saved on your phone storage.

I hope it would solve your problem. If it was your desired solution please vote me up:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM