- Creatively Nino
- Feb 27, 2021
- 3 min read
Want to know in-depth details on how you can set up likes on your custom blog feed for logged-in members and how to keep track of them by using Wix Code a.k.a. Velo??
Here is the helpful code to get you going! Let me know if you need any more assistance in the comments on YouTube or contact me at the bottom today!
📚 WHAT WAS COVERED:
00:00 Awesome Intro
01:45 Add Elements to Editor and Repeater
03:02 Create a Post Likes Database
04:30 Create a Before Insert Hook on the Post Likes Database
07:13 Add Custom Like Code using Velo
11:43 Find Database ID & Permission Settings
14:40 Custom Like Code using Velo
24:20 Save and Preview Results in Preview Mode
Code Snippet to follow along with the video:
Check out my customize blog feed code here to know other information about how to populate the repeater with Wix blog data.
YouTube Video: https://bit.ly/3aUq4sa
Page Code
This is the repeater page code that has the like code.
export async function Repeater1_itemReady($item, itemData, index) {
// Add your code for this event here:
let defaultImage = $w("#image").src;
$item("#image").src = await (itemData.coverImage) ? itemData.coverImage : defaultImage;
$item("#image").alt = await (itemData.title.length > 50) ? itemData.title.slice(0, 47) + "..." : itemData.title;
$item("#image").tooltip = await (itemData.title.length > 50) ? itemData.title.slice(0, 47) + "..." : itemData.title;
$item("#daysAgo").text = await (itemData.lastPublishedDate) ? timeAgo(itemData.lastPublishedDate).toString() : "";
$item("#title").text = await (itemData.title.length > 50) ? itemData.title.slice(0, 47) + "..." : itemData.title;
$item("#excerpt").text = await (itemData.excerpt.length > 150) ? itemData.excerpt.slice(0, 147) + "..." : itemData.excerpt;
//console.log(itemData.categories)
if (itemData.categories.length > 0) {
let categoryList = [];
for (var i = 0; i < itemData.categories.length; i++) {
let info = await loadRepeaterCategories(itemData.categories[i])
await categoryList.push({ "label": info, "value": info })
}
if (categoryList.length > 0) {
$item("#categoriesRepeater").options = await categoryList
$item("#categoriesRepeater").show()
} else {
$item("#categoriesRepeater").hide()
}
} else {
$item("#categoriesRepeater").options = []
$item("#categoriesRepeater").hide()
}
$item("#title").onClick((event) => {
wixLocation.to(itemData["postPageUrl"])
})
$item("#image").onClick((event) => {
wixLocation.to(itemData["postPageUrl"])
})
// like code
const isliked = $item("#vectorImage34");
const isnotliked = $item("#vectorImage33");
const likedBox = $item("#box13");
//const collectionId = "Blog/Posts";
const collectionId1 = "PostLikesData";
const LikeStatus = {
default: 'default',
active: 'active'
};
let switchlike;
let getLike = await wixData.query(collectionId1).eq("userId", wixUsers.currentUser.id).eq("postId", itemData._id).find();
let likeInfo = (getLike.items[0]) ? getLike.items[0] : null;
switchlike = (getLike.items.length > 0) ? LikeStatus.active : LikeStatus.default;
setLikeStatus(switchlike);
likedBox.onClick(async (event) => {
if (isnotliked.hidden) { //removing like
setLikeStatus(LikeStatus.default)
try {
wixData.remove(collectionId1, likeInfo._id).then((res) => {
if (res) {
return console.log("post was unliked")
//it was removed
} else {
return Promise.reject("Did not remove")
//it wasn't removed
}
})
} catch (error) {
console.log(error);
setLikeStatus(LikeStatus.active);
}
} else { //adding like
if (wixUsers.currentUser.loggedIn) {
applyLike(wixUsers.currentUser.id, itemData._id);
} else {
let options = { "mode": "signup", "lang": "es" };
wixUsers.promptLogin(options)
.then((user) => {
let userId = user.id; // "r5me-6fem-45jf-djhe-484349"
let isLoggedIn = user.loggedIn; // true
applyLike(userId, itemData._id);
})
.catch((err) => {
let errorMsg = err; // "The user closed the login dialog"
console.log(err);
});
}
function applyLike(userId, postId) {
setLikeStatus(LikeStatus.active)
try {
let likeupload = { "userId": userId, "postId": postId };
wixData.insert(collectionId1, likeupload).then((res) => {
if (res) {
likeInfo = res;
return console.log("post was liked")
//it was inserted
} else {
return Promise.reject("Did not insert")
//it wasn't inserted
}
})
} catch (error) {
console.log(error);
setLikeStatus(LikeStatus.default);
}
}
}
});
function setLikeStatus(state) {
switch (state) {
case LikeStatus.default:
isliked.hide();
isnotliked.show();
break
case LikeStatus.active:
isnotliked.hide();
isliked.show();
break
}
}
}
Backend Code
This code is to be added to the data.js backend file that is located in your code files.
import wixData from 'wix-data';
let optionsTT = {
"suppressAuth": true,
"suppressHooks": true
};
export async function PostLikesData_beforeInsert(item, context) {
//This code is here to stop duplicate likes from saving into the database.
const { items } = await wixData.query("PostLikesData")
.eq("userId", item.userId)
.eq("postId", item.postId)
.find(optionsTT);
if (items.length) { //statement means that if something comes from the query above then it will reject because it has found information.
return Promise.reject("Duplicated Likes Forbidden");
}
//if nothing else is found then return the item to be inserted into the database
return item;
}
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
📺 MY PLAYLISTS :
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
💻 WEBSITE
Check out more of the website. If you have a question, let's chat it up below! More information coming soon so stay tuned!
Comments