How can i fetch reaction count? - javascript

Hey just having issues with fetching reaction count i have this
const getStats = (message) => {
return Promise.all([
message.reactions.resolve(SUGGESTIONS.EMOJI.UP_VOTE).fetch(),
message.reactions.resolve(SUGGESTIONS.EMOJI.DOWN_VOTE).fetch()
]).then(([fetchedReaction, fetchedReaction2]) => {
const upVotes = fetchedReaction.count - 1;
const downVotes = fetchedReaction2.count - 1;
return [upVotes, downVotes];
});
}
but im getting TypeError: Cannot read properties of null (reading 'fetch')
i have tryed using count instead fetch but still getting count as null

Related

React app crashing when trying to read total property

I am trying to figure out how to solve this issue where the app is crashing when trying to read the 'total' property. The problem is that the issue is not happening when I am viewing in development. But when I deploy to Heroku, it happens. Any idea what it could be?
const determineDefaultQuote = () => {
const exchangeInternalAccount = holdingsByAccount.find(account => account.exchange === 'EXCHANGE');
const usdcBalance = exchangeInternalAccount && exchangeInternalAccount.assets.find(item => item.name === 'USD').freeTotal;
const usdtBalance = exchangeInternalAccount && exchangeInternalAccount.assets.find(item => item.name === 'SHIB').freeTotal;
if (usdBalance > shibBalance) return 'USD';
return 'SHIB';
};
The error I am seeing is:
main.d3a0d78b.js:1 uncaught at q TypeError: Cannot read properties of undefined (reading 'freeTotal')

TypeError: Cannot read property 'members' of undefined in discord.js \\\

const guild = client.guilds.cache.get("771238821550620703");
setInterval(function () {
var memberCount = guild.members.filter(member => !member.user.bot).size;
var memberCountChannel = client.channels.get("886555053421375501");
memberCountChannel.setName(`╭・🍸:Online :${memberCount}`);
}, 10000);
TypeError: Cannot read property 'members' of undefined
I have checked the channel id and server id hundred times but it is still not working..
client.channels.get(...) is not a function. The correct method would be client.channels.cache.get(...).
You should always fetch the guild instead of searching the cache, especially as more guilds get added.
Example:
(async () => {
const guild = await client.guilds.fetch("771238821550620703");
setInterval(function () {
var memberCount = guild.members.filter(member => !member.user.bot).size;
var memberCountChannel = guild.channels.get("886555053421375501");
memberCountChannel.setName(`╭・🍸:Online :${memberCount}`);
}, 10000);
});

Uncaught Syntax errors

I am working on a quiz app for class and I keep getting the error "Uncaught SyntaxError: Unexpected token o in JSON at position 1" in the console. I have tried looking up YouTube videos for solutions and have even tried fixing the code through similar posts on this site. I am at a loss and can't figure out what is wrong.
const username = document.querySelector('#username');
const saveScoreBtn = document.querySelector('#saveScoreBtn');
const finalScore = document.querySelector('#finalScore');
const mostRecentScore = localStorage.getItem('mostRecentScore');
const highScores = JSON.parse(localStorage.getItem('highScores')) || [];
const MAX_HIGH_SCORES = 5;
finalScore.innerText = mostRecentScore;
username.addEventListener('keyup', () => {
saveScoreBtn.disabled = !username.value;
});
saveHighScore = e => {
e.preventDefault();
const score = {
score: mostRecentScore,
name: username.value
};
highScores.push(score);
highScores.sort((a,b) =>{
return b.score - a.score;
})
highScores.splice(5);
localStorage.setItem('highscores', JSON.stringify(highScores));
window.location.assign('../high-scores/highscores.html')
};
"Uncaught SyntaxError: Unexpected token o in JSON at position 1"
That means this is not json formated code. Check your json again.

TypeError: Cannot read property 'NaN' of undefined

I'm getting issues with this code. It gives me the following error:
TypeError: Cannot read property 'NaN' of undefined
dotenv.config();
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", async (msg) => {
const tokens = msg.content.split(" ");
if (tokens[0] === "!gif") {
const keywords = tokens.slice(1, tokens.length).join(" ");
const url = `https://api.tenor.com/v1/search?q=${keywords}&key=${process.env.EK3M4TY0S70Y}&limit=10`;
const response = await fetch(url);
const result = await response.json();
const index = Math.floor(Math.random() * result.length);
msg.channel.send(result.results[index].url);
}
});
Property NaN
The NaN in your code is the variable index. If result.length is undefined then Math.floor(Math.random() * result.length) will be NaN.
When you try to get an item from the array you are using result.results[index] which implies that result is an object with a results property which is an array. So the result itself is not an array and accessing result.length doesn't make sense. You would want result.results.length`.
Of undefined
The error "Cannot read property 'NaN' of undefined" comes from result.results[index]. so if index is the NaN property then result.results is the undefined value. The Tenor API should return an object with a results property, so this is likely due to a malformed request. If you have an invalid key for example, your response will be an object with a property error and no results. You could also have an invalid q, so you'll want to escape it with encodeURIComponent.
I don't have enough information to know why the request is failing for you, but we can check that we have an array and console.log the result otherwise so that you can inspect it (or throw an Error). When you improve the code a bit more you'll want to introduce try/catch blocks.
const testFunc = async (msgContent, apiKey = "") => {
const tokens = msgContent.split(" ");
if (tokens[0] === "!gif") {
const keywords = encodeURIComponent(
tokens.slice(1, tokens.length).join(" ")
);
// seems to work with no key at all
const url = `https://api.tenor.com/v1/search?q=${keywords}&key=${apiKey}&limit=10`;
const response = await fetch(url);
const result = await response.json();
if ("results" in result) {
const images = result.results;
const index = Math.floor(Math.random() * images.length);
return images[index].url;
} else {
console.log("Invalid Response", result);
}
}
};
testFunc("!gif cat", "").then(console.log);

Firebase Uncaught TypeError: Cannot read property 'forEach' of undefined

I'm trying to count the number of misbehavior on the two routes I've made in my database. Below are the structure of my firebase database under drivers and reports database respectively:
[drivers database] - i.stack.imgur.com/Q6GKs.png
[reports database] - i.stack.imgur.com/ALWPu.png
Here's my counter for counting the number of misbehavior:
<script>
var route1Count = 0;
var route2Count = 0;
var drivers;
var reports;
var driversRef = firebase.database().ref('drivers/');
var reportsRef = firebase.database().ref('reports/');
driversRef.once('value', (snapshot) => {
drivers = snapshot;
});
reportsRef.once('value', (snapshot) => {
reports = snapshot;
});
drivers.forEach((driver) => {
var violationCount = reports.filter((report) => report.val().plateNumber === driver.key).length;
if(driver.val().route === "Fairview - Quiapo"){
route1Count += violationCount;
}else if(driver.val().route === "Quiapo - Fairview"){
route2Count += violationCount;
}
});
document.getElementById("demo").innerHTML = "route1: " + route1Count + "route2: " + route2Count;
</script>
I get this error message:
Uncaught TypeError: Cannot read property 'forEach' of undefined
at drivers.forEach, all inputs will be greatly appreciated! Thanks!
Error Message :
you could nest them, or if you run this in an environment that supports es6's Promise object (which your code suggests), you could use the once() returning a promise and more elegantly do:
Promise.all([driversRef.once('value'), reportsRef.once('value')])
.then(([driversSnapshot, reportsSnapshot]) => {
// ...
})

Categories