How to use storage? correctly by WeChat Mini Programs

problem description

in project development, you like to save some data selected by users. Storage local cache is used here. The next time you open Mini Program, you can use storage to obtain and assign values to data data. However, every time you modify and save, you have to modify both the data in data and the data in storage, which feels bloated. I would like to ask the bosses what method they use to deal with this problem, and perhaps there is no such binding that automatically changes the data in the storage when changing the data.

Apr.01,2021

I do this by implementing a method in app.js to handle this kind of data, such as login information:

// app.js
App({
    //...
    setupLogin: function(data, cb) {
        if (data) {
            // 
            wx.setStorageSync('loginData', data)
        } else {
            // storage
            data = wx.getStorageSync('loginData')
        }

        if (data && data != [] && data != "") {
            this.globalData.loginData = data
        } else {
            this.globalData.loginData = null
        }

        if (cb) {
            cb()
        }
    }
})

call setupLogin every time Mini Program loads, and save the data in app.globalData , which makes it easier to get when you need it. Here, I will determine whether a login operation is required based on whether app.globalData.loginData is null .

you can also do this if you need to work with other similar data.

of course, you can also encapsulate a method to specifically implement this series of operations.

Menu