Wechat applet like function

Posted by Stickybomb on Thu, 03 Feb 2022 00:32:19 +0100

Recently, I was working on a simple posting applet, which involves the like function. At first, I thought it was very simple. Later, I found that the difficulty lies in how to record the user's like status of the article, so as to avoid the failure of the like status when I open it next time. Let's start with the renderings:


After Baidu for half an hour, it is found that the cache of applet can be used to solve this problem, and a new cache object likeCollection is created

// First get the object from the local cache. If not, create an empty object for it (indicating that the user enters the applet for the first time)
let likeCollection = wx.getStorageSync('likeCollection');
    if(!likeCollection){
      wx.setStorageSync('likeCollection', {})
    }

Get the article object array from the background and assign it to the variable list

// Applet data attribute
data:{
  list:[]
}
// Call cloud function
    wx.cloud.callFunction({
      name:'getLists',
    }).then(res=>{
    this.setData({
       list:res.result.data; // Assign to list
})
    }).catch(reason=>{console.log(reason)});

Here, we add an attribute to each element object of the obtained list: "hasChange". Note that the type is boolean. The data given in the background does not have this attribute. The value is obtained from likeCollection, and the key is based on the attribute of the article object_ id. for cloud development used in the background, the cloud database provides one for each record by default_ id is the unique identifier, that is, the primary key in the relational database. This statement should be written in the onload() function and executed when the page is loaded.

// list is an array of article objects sent from the background, which is not specifically described here```
this.data.list.forEach((item)=>{
        item['hasChange']=likeCollection[item._id];
      })

The key here is that if you like it before, the corresponding article cache value in likeCollection is true. If you don't like it, assign undefined to the list. If you cancel the like, the value becomes fasle. In JS, undefined == false
On the applet page, use the attribute "hasChange" to judge whether you like it, and display the corresponding pictures and numbers:

 <image src='{{item.hasChange?favor_img:favor}}' class='like' bindtap='praiseThis'

As can be seen from the above code, each like image is bound with a click event bindtap = 'pracethis'. This event method is the key. See the code below

// Praise function
  praiseThis(e){
      var that = this;
      let list = e.currentTarget.dataset.list;
      let index = e.currentTarget.dataset.index;
      let _id = e.currentTarget.dataset._id;
      let hasChange = !(this.data[list][index].hasChange);
        // The currently clicked likes are reversed
        console.log('Currently clicked likes'+hasChange)
     // Judge whether local users like the article
      wx.getStorage({
       key: 'likeCollection',
       success:(res)=>{
        let details = res.data;
        console.log('Value in cache:'+details[_id])
        var onum = parseInt(that.data[list][index].clickload);
        if(details[_id]){  // If you like it, you can cancel it
           that.data['list'][index].clickload = (onum - 1);
           that.data['list'][index].hasChange = false;
        }
          else {
          // If you don't like it, the amount of praise will be increased by one
           that.data['list'][index].clickload = (onum + 1);
           that.data['list'][index].hasChange = true;
         } 
         // However, add / modify the value of the corresponding article to the cache object likeCollection and save the state
         wx.getStorage({
           key: 'likeCollection',
           success:datas=>{
             let obj = datas.data;
             obj[_id] = that.data['list'][index].hasChange
             wx.setStorage({
               data: obj,
               key: 'likeCollection',
               success:res=>{
                 
                 console.log('Cache successful')
               },
               fail:reason=>console.log(reason)
             })
           }
         })
         this.setData({
          list: that.data.list,
         }) 
         //Call the cloud function to increase or decrease the number of hits of articles in the background
         wx.cloud.callFunction({
           name:'pariseThis',
           data:{
             _id:_id,  //Article id
             likeOr:that.data[list][index].hasChange,
           }
         }).then(res=>{
           console.log(res.result)
          // Dynamic update praise
     
         }).catch(reason=>{
           console.log(reason)
         });
       }
     })
  
  },

Here's how the key value in the cache object likeCollection changes when you like it:

For the first time, each article is in the state of not liking. At this time, the cache object likeCollection is an empty object:

Next, let's praise the two articles. At this time, the value of likeCollection has changed:

As you can see, there are two main articles inserted in it_ If the id is the key name and the value is true, cancel a like below:

Re like and cancel another like:

Well, here, the simple like function is basically realized.
To sum up, after obtaining the article data from the background, according to the article data from the cache object likeCollection_ id queries the like status. If you haven't like it, the_ The id attribute is undefined, false after cancellation, and true after likes; When the page is loaded, assign the state stored in the cache to the custom attribute "hasChange" of the corresponding article

Topics: Javascript Programming css3 ECMAScript html