Last active
August 4, 2020 19:23
-
-
Save GlenMerlin/3e91a869bfa243ac85c3c1dbe5d7a5fd to your computer and use it in GitHub Desktop.
Same as my other like gist but without using jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from "axios" | |
var failedAttemptCount = 0 | |
class Like { | |
constructor() { | |
if (document.querySelector(".like-box")) { | |
axios.defaults.headers.common["X-WP-Nonce"] = universityData.nonce | |
this.events() | |
} | |
} | |
events() { | |
document.querySelector(".like-box").addEventListener("click", e => this.ourClickDispatcher(e)) | |
} | |
// methods | |
ourClickDispatcher(e) { | |
let currentLikeBox = e.target | |
while (!currentLikeBox.classList.contains("like-box")) { | |
currentLikeBox = currentLikeBox.parentElement | |
} | |
if (currentLikeBox.getAttribute("data-exists") == "yes") { | |
this.deleteLike(currentLikeBox) | |
} else { | |
this.createLike(currentLikeBox) | |
} | |
} | |
async createLike(currentLikeBox) { | |
try { | |
const response = await axios.post(universityData.root_url + "/wp-json/university/v1/manageLike", { "professorId": currentLikeBox.getAttribute("data-professor") }) | |
if (response.data != "Only logged in users can create a like.") { | |
currentLikeBox.setAttribute("data-exists", "yes") | |
var likeCount = parseInt(currentLikeBox.querySelector(".like-count").innerHTML, 10) | |
likeCount++ | |
currentLikeBox.querySelector(".like-count").innerHTML = likeCount | |
currentLikeBox.setAttribute("data-like", response.data) | |
} | |
console.log(response.data) | |
} catch (e) { | |
alert("Oops something went wrong :( \nAre you logged in?") | |
console.log(response) | |
failedAttemptCount++ | |
console.log(failedAttemptCount) | |
if (failedAttemptCount >= 2) { | |
window.location.href = universityData.root_url + '/wp-login.php?action=register'; | |
} | |
console.log("Sorry") | |
} | |
} | |
async deleteLike(currentLikeBox) { | |
try { | |
const response = await axios.delete(universityData.root_url + "/wp-json/university/v1/manageLike", { data: { "like": currentLikeBox.getAttribute("data-like") } }) | |
currentLikeBox.setAttribute("data-exists", "no") | |
var likeCount = parseInt(currentLikeBox.querySelector(".like-count").innerHTML, 10) | |
likeCount-- | |
currentLikeBox.querySelector(".like-count").innerHTML = likeCount | |
currentLikeBox.setAttribute("data-like", "") | |
console.log(response.data) | |
} catch (e) { | |
console.log(e) | |
} | |
} | |
} | |
export default Like |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment