I have this embed:
var msgArr = [];
var embed = new Discord.MessageEmbed()
.setTitle('Foo')
.setDescription('Bar')
.setTimestamp();
message.channel.send(embed).then(sentMessage => {
msgArr.push(sentMessage);
});
Which is then edited:
embed = new Discord.MessageEmbed()
.setTitle('Bar')
.setDescription('Foo')
.setTimestamp();
msgArr[0].edit(embed);
This editing process is repeated multiple times on a loop:
var counter = 0;
const frequency = 30000;
setInterval(function () {
if (counter++ % 2 == 0) {
embed = new Discord.MessageEmbed()
.setTitle('Bar')
.setDescription('Foo')
.setTimestamp();
msgArr[0].edit(embed);
} else {
embed = new Discord.MessageEmbed()
.setTitle('Foo')
.setDescription('Bar')
.setTimestamp();
msgArr[0].edit(embed);
}
}, frequency);
(Basically the title and the description switch between 'Foo' and 'Bar' every 30 seconds, with a .setTimestamp included)
Now, what happens when I run this is that the .setTimestamp will work fine for the first minute or 2, then it starts to 'lag' behind the actual time. Can anyone help me figure out the reason for this?
Full Code (Yes there have been some parts cut out, but there are related to API things that have no effect on the embed part):
// Some code is commented out due to requests you have made, it should be obvious which code this is. I haven't cleaned up the commented out code, therefore be warned there will be some variables that aren't in this.
const Discord = require('discord.js');
// Below is normally not constant
const itemAmount = 6;
module.exports = {
name: 'command',
cooldown: 1,
description: 'Test Description',
execute(message) {
function sendEmbeds(channel1, channel2) {
message.client.channels.cache.get(channel1).bulkDelete(8);
for (let i = 0; i < 1; i++) {
let now = new Date();
let embed = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can **buy** with `Bits` and then **sell** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some url')
.addFields(
{ name: 'Information:', value: 'Buy Price: `1500 Bits`\n Sell Price: `250000 Coins` \n Coins per Bit Spent: `250 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
// Next if statement is api related, but since it's important to the embed it'll stay
if (itemAmount >= 5) {
embed.setTitle(i + 1 + '. **HARD TO SELL**: Item');
}
message.client.channels.cache.get(channel1).send(embed).then(sentMessage => {
msgArr.push(sentMessage);
});
}
message.client.channels.cache.get(channel2).bulkDelete(5);
for (let i = 0; i < 1; i++) {
let now = new Date();
var craftableEmbed = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can craft by **buying** `' + craftables[craft[i][0]]["amountNeeded"] + ' ' + craftables[craft[i][0]]["itemNeeded"]["name"] + '` from the lowest BIN, buying `' + craftables[craft[i][0]]["bitsItem"] + '` with `Bits` and then **selling** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some thumbnail')
.addFields(
{ name: 'Information:', value: 'Bits Buy Price: `1200 Bits` \n Item Buy Price: `500000 Coins` \n Sell Price Per Crafted Item: `600000 Coins` \n Profit Per Craft: `746889 Coins` \n Coins per Bit Spent: `153.6 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
message.client.channels.cache.get(channel2).send(craftableEmbed).then(sentMessage => {
msgArrCraft.push(sentMessage);
});
}
}
function editEmbeds() {
for (let i = 0; i < 1; i++) {
let now = new Date();
console.log(now);
let embedNew = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can **buy** with `Bits` and then **sell** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some thumbnail')
.addFields(
{ name: 'Information:', value: 'Buy Price: `1500 Bits`\n Sell Price: `250000 Coins` \n Coins per Bit Spent: `250 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
if (itemAmount >= 5) {
embedNew.setTitle(i + 1 + '. **HARD TO SELL**: Item');
}
msgArr[i].edit(embedNew).then(newEmbed => {
msgArr[i] = newEmbed;
console.log(now, 'edited');
});
}
for (let i = 0; i < 1; i++) {
let now = new Date();
console.log(now);
let craftableEmbedNew = new Discord.MessageEmbed()
.setColor('#141414')
.setTitle(i + 1 + '. Item')
.setDescription(now.toString())
// .setDescription('This is an item you can craft by **buying** `' + craftable[craft[i][0]]["amountNeeded"] + ' ' + craftable[craft[i][0]]["itemNeeded"]["name"] + '` from the lowest BIN, buying `' + craftable[craft[i][0]]["bitsItem"] + '` with `Bits` and then **selling** as a `BIN` for easy Skyblock Coins \n ━━━━━━━━━━━━━━━━━━━━━━━━━━━━')
.setThumbnail('some thumbnail')
.addFields(
{ name: 'Information:', value: 'Bits Buy Price: `1200 Bits` \n Item Buy Price: `500000 Coins` \n Sell Price Per Crafted Item: `600000 Coins` \n Profit Per Craft: `746889 Coins` \n Coins per Bit Spent: `153.6 Coins`', inline: true },
)
.setTimestamp(now)
.setFooter('Powered by - SKY | Brokers', 'https://cdn.discordapp.com/icons/715801930877894706/a_95042b5d9aee771fdddec12191fb6092.webp?size=128');
msgArrCraft[i].edit(craftableEmbedNew).then(newEmbed => {
msgArr[i] = newEmbed;
console.log(now, 'edited');
});
}
}
var msgArr = [];
var msgArrCraft = [];
setTimeout(() => {
// Embed
// The bot uses 2 channels, if you are testing this be warned that it is coded to delete 8 messages in the first channel, and 5 messages in the second. (Replace the channel IDs with the ones you are testing in)
sendEmbeds('ChannelID1', 'ChannelID2');
}, 15000);
var counter = 0;
const frequency = 30000;
setInterval(function () {
// Normally this if statement has API related code, this is omitted here therefore it seems useless.
if (counter++ % 2 == 0) {
editEmbeds();
}
else {
editEmbeds();
}
}, frequency);
},
};
If you would like the COMPLETE full code (included a ton of API related things) feel free to ask.
Related
I am using the syncfusion to do the Scheduler calendar in the react code to block specific time intervals or days. Below the code is worked to block specific time intervals or days following by Subject, Doctor,StartTime, EndTime,RecurrenceRule and IsBlock in the return value, But this method just can follow each Doctor to block the date or time.
May I know how to block all doctors following by Subject, Doctor(This one how can choose all the doctor together),StartTime, EndTime,RecurrenceRule and IsBlock in my existing code? I set all doctor's values as dash -.
Below is my existing code to block specific time intervals or days following by Subject, Doctor,StartTime, EndTime,RecurrenceRule and IsBlock in the return value:
const getOrganizer = useCallback(() => {
getSchedulerOrganizerList().then((response) => {
var data = response.data;
setOrganizerList(
data.map((schedulerBlock) => {
var startDate = new Date(
formatDateStringAsDate2(schedulerBlock.startDate)
);
var endDate = new Date(
formatDateStringAsDate2(schedulerBlock.stopDate)
);
var count = null;
var repeatType = schedulerBlock.repeatType.toUpperCase();
if (repeatType === "DAILY") {
var Difference_In_Days = getDayDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Days;
} else if (repeatType === "WEEKLY") {
var Difference_In_Weeks = getWeekDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Weeks;
} else if (repeatType === "MONTHLY") {
var Difference_In_Months = getMonthDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Months;
} else if (repeatType === "YEARLY") {
var Difference_In_Years = getYearDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Years;
} else if (repeatType === "ONE TIME") {
repeatType = "ONE TIME";
}
var formatStopDate = moment(schedulerBlock.stopDate).format("YYYY-MM-DD");
var formatStopTime = moment(schedulerBlock.stopTime).format("HH:mm:ss");
var stopTimeValue = formatStopDate + "T" + formatStopTime;
var recurrenceRule = repeatType === "ONE TIME" ? null : "FREQ=" + repeatType + count;
var endTimeValue = repeatType === "ONE TIME" ? formatDateTimeStringAsDateTime(stopTimeValue) : formatDateTimeStringAsDateTime(schedulerBlock.stopTime);
return {
Id: schedulerBlock.id,
Subject: schedulerBlock.reason,
Doctor: schedulerBlock.doctor,
StartTime: formatDateTimeStringAsDateTime(schedulerBlock.startDate),
EndTime: endTimeValue,
RecurrenceRule: recurrenceRule,
IsBlock: true,
};
})
);
});
}, []);
Below is my sample return value for Dr X:
{
"Id": 19,
"Subject": "Test",
"Doctor": "Dr X",
"StartTime": "15 Aug 2022 09:00 PM",
"EndTime": "15 Aug 2022 11:00 PM",
"RecurrenceRule": "FREQ=WEEKLY;COUNT=8",
"IsBlock": true
}
Below are my current code results, in the calendar view I have 3 doctors which are Dr X, Dr Y, and Dr Z. I have blocked the Dr X at 9PM - 11 PM (August 15, 2022).
Now I am trying to do to block all doctors following by Subject, Doctor(This one how can choose all the doctor together),StartTime, EndTime,RecurrenceRule and IsBlock in my existing code I set all doctor's values as dash -, below coding is what I am trying, I try to hardcode the value - to test, but it doesn't work.
const getOrganizer = useCallback(() => {
getSchedulerOrganizerList().then((response) => {
var data = response.data;
setOrganizerList(
data.map((schedulerBlock) => {
var startDate = new Date(
formatDateStringAsDate2(schedulerBlock.startDate)
);
var endDate = new Date(
formatDateStringAsDate2(schedulerBlock.stopDate)
);
var count = null;
var repeatType = schedulerBlock.repeatType.toUpperCase();
if (repeatType === "DAILY") {
var Difference_In_Days = getDayDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Days;
} else if (repeatType === "WEEKLY") {
var Difference_In_Weeks = getWeekDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Weeks;
} else if (repeatType === "MONTHLY") {
var Difference_In_Months = getMonthDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Months;
} else if (repeatType === "YEARLY") {
var Difference_In_Years = getYearDiff(startDate, endDate) + 1;
count = ";COUNT=" + Difference_In_Years;
} else if (repeatType === "ONE TIME") {
repeatType = "ONE TIME";
}
var formatStopDate = moment(schedulerBlock.stopDate).format("YYYY-MM-DD");
var formatStopTime = moment(schedulerBlock.stopTime).format("HH:mm:ss");
var stopTimeValue = formatStopDate + "T" + formatStopTime;
var recurrenceRule = repeatType === "ONE TIME" ? null : "FREQ=" + repeatType + count;
var endTimeValue = repeatType === "ONE TIME" ? formatDateTimeStringAsDateTime(stopTimeValue) : formatDateTimeStringAsDateTime(schedulerBlock.stopTime);
var schedulerBlockDoctor = schedulerBlock.doctor;
if (schedulerBlockDoctor === "-"){
var schedulerBlockDoctor = " ";
}
return {
Id: schedulerBlock.id,
Subject: schedulerBlock.reason,
Doctor: schedulerBlockDoctor,
StartTime: formatDateTimeStringAsDateTime(schedulerBlock.startDate),
EndTime: endTimeValue,
RecurrenceRule: recurrenceRule,
IsBlock: true,
};
})
);
});
}, []);
I want the expected result like below the picture if I choose all doctors to need to block at the same time and date (all doctors value is put dash - to declare),
Hope anyone can guide me on how to solve this problem, is possible to get a simple way to edit my existing code? Thanks.
So I have a command for my discord music bot, here's the command:
run: async function (client, message, args) {
let channel = message.member.voice.channel;
if (!channel) return sendError("I'm sorry but you need to be in a voice channel to play music!", message.channel);
const lofiSongs = ["listen before i go billie","Billie Eilish ~ No Time To Die Slowed to Perfection","Billie Eilish - Six Feet Under ","Chelsea Cutler - Crazier Things","All Kids Are Depressed (Slowed to Perfection)","Close To You- The Carpenters (ukulele cover) | Reneé Dominique","the hills || slowed","Powfu - Death Bed (Slowed To Perfection)","maroon 5 - memories (slowed + reverb)","Ashe - Moral Of The Story (Slowed + Lyrics)","Olivia Rodrigo - traitor (Lyrics)","kina - can we kiss forever [slowed + reverb]","Claire Rosinkranz - Backyard Boy (Lyrics)","comethru - jeremy zucker cover by kimswizzled","[DOXTAPE] Maddox(마독스) - At My Worst (Pink Sweat$ Cover)","Be Alright by Dean Lewis | acoustic cover by Jada Facer","The One That Got Away by Katy Perry | cover by Jada Facer","Let Her Go - Passenger (Official Video Cover by Jasmine Thompson)","Can't Help Falling In Love | Elvis Presley (cover)","IT'S YOU - ALI GATIE[slowed + reverb]starmilk","All Kids Are Depressed (Slowed to Perfection)","billie eilish khalid - lovely","Duncan Laurence - Arcade","yellow","Heartbreak Anniversary","dancing with your ghout","heater tate macrae","hold on","watch billie eilish","martin and gina slowed reverb","Kali Uchis - telepatía (Cover by Lesha)","leaving on a jet plane macarone project","fly me to the moon yungrythm","close to you renee dominnique","blue moon jaritenph remix","run away","let me down slowely","little do you know","gnash feat. Olivia o'brien - I hate u, I love u (Consoul Trainin Remix)","ocaen eyes","hostage","remendy of broken heart","jocelyn floers","CKay - Love Nwantiti (Acoustic Version)","Tate McRae - friends don’t look at friends that way"]
const randomLofi = lofiSongs[Math.floor(Math.random() * lofiSongs.length)];
var searched = await yts.search(randomLofi)
const msg = message
const url = "";
var serverQueue = message.client.queue.get(message.guild.id);
let songInfo = null;
let song = null;
if (url.match(/^(https?:\/\/)?(www\.)?(m\.)?(youtube\.com|youtu\.?be)\/.+$/gi)) {
try {
songInfo = await ytdl.getInfo(url);
if (!songInfo) return sendError("Looks like i was unable to find the song on YouTube", message.channel);
song = {
id: songInfo.videoDetails.videoId,
title: songInfo.videoDetails.title,
url: songInfo.videoDetails.video_url,
img: songInfo.player_response.videoDetails.thumbnail.thumbnails[0].url,
duration: songInfo.videoDetails.lengthSeconds,
ago: songInfo.videoDetails.publishDate,
views: String(songInfo.videoDetails.viewCount).padStart(10, " "),
req: message.author,
};
} catch (error) {
console.error(error);
return message.reply(error.message).catch(console.error);
}
} else {
try {
songInfo = searched.videos[0];
song = {
id: songInfo.videoId,
title: Util.escapeMarkdown(songInfo.title),
views: String(songInfo.views).padStart(10, " "),
url: songInfo.url,
ago: songInfo.ago,
img: songInfo.image,
req: message.author,
};
} catch (error) {
console.error(error);
return message.reply(error.message).catch(console.error);
}
}
if (serverQueue) {
serverQueue.songs.push(song);
let thing = new MessageEmbed()
.setAuthor("Song has been added to queue")
.setThumbnail(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Duration", song.duration, true)
.addField("Playlist", "Lofi")
.setFooter(`Views: ${song.views} | ${song.ago}`);
return message.channel.send(thing);
}
const queueConstruct = {
textChannel: message.channel,
voiceChannel: channel,
connection: null,
songs: [],
volume: 80,
playing: true,
loop: true,
};
message.client.queue.set(message.guild.id, queueConstruct);
queueConstruct.songs.push(song);
const play = async (song) => {
const queue = message.client.queue.get(message.guild.id);
if (!song) {
message.client.queue.delete(message.guild.id);
return;
}
let stream = null;
if (song.url.includes("youtube.com")) {
stream = await ytdl(song.url);
stream.on("error", function (er) {
if (er) {
if (queue) {
queue.songs.shift();
play(queue.songs[0]);
return sendError(`An unexpected error has occurred.\nPossible type \`${er}\``, message.channel);
}
}
});
}
queue.connection.on("disconnect", () => message.client.queue.delete(message.guild.id));
const dispatcher = queue.connection.play(ytdl(song.url, { quality: "highestaudio", highWaterMark: 1 << 25, type: "opus" })).on("finish", () => {
const shiffed = queue.songs.shift();
if (queue.loop === false) {
queue.songs.push(shiffed);
}
play(queue.songs[0]);
});
dispatcher.setVolumeLogarithmic(queue.volume / 100);
let thing = new MessageEmbed()
.setAuthor("PussyMusic Has Started Playing Music")
.setImage(song.img)
.setColor("#fffdd0")
.addField("Name", song.title, true)
.addField("Views", song.views, true)
.addField("Requested by", song.req.tag, true)
.setFooter(`PussyMusic`);
queue.textChannel.send(thing);
};
try {
const connection = await channel.join();
queueConstruct.connection = connection;
play(queueConstruct.songs[0]);
} catch (error) {
console.error(`I could not join the voice channel: ${error}`);
message.client.queue.delete(message.guild.id);
await channel.leave();
return sendError(`I could not join the voice channel: ${error}`, message.channel);
const executeTimes = 5;
for (let i = 0; i < executeTimes; i++) {
<Command>.execute(...);
}
}
}
};
Im pretty new to coding, sorry for my bad knowledge.
As I said I want the command to run X times, Example:
!Command 4 (will run the command 4 times, It means the bot should play 4 songs)
I realy struggle with this code, so thanks if you're helping :)
Simplest way (and maybe buggy way) is to just create for loop for it.
Personal note: I would add cap to the times people can use the command, to avoid spam and possible rate limit issues.
For loop basically can be as simple as:
if(!isNaN(args[0]){
for (let i = 0; i < args[0]; i++){
//Run rest of your code here
}
}
There is not much to go on with your current questions code, so this is the simplest way I can imagine explaining this. Create for loop for it and cap it to prevent spam
First of all, normal discord.js stuff seems to not work in my code.
So I want to make it so that the user calls the command, the bot replies and deletes the user's message ,that called the command, as well.
bot.on('message', function (user, userID, channelID, message, evt) {
if (message.substring(0, 1) == '?') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
case 'gw':
var gw = args.slice(1).join(' ');
var thumb = args[0];
let date = new Date();
let smalldate = date.getDate() + '/' + (date.getMonth() +1) + ' | ' + date.getHours() + ':' + date.getMinutes();
bot.sendMessage({
to: channelID,
message: `\n <#&${'806183931065401405'}>` + `\n` + `\n 🎉 __**Giveaway**__ 🎉`,
embed: {
color: 16580705,
footer: {
text: 'Started On : ' + smalldate,
},
thumbnail:{
url : thumb
},
title: gw,
description: 'Hosted By: ' + user,
}
});
bot.deleteMessage(message);
}
}
});
Thank you from the core of my heart for any replies.
As I discussed in my comment, here are the changes:
bot.on('message', message => {// arrow function
if (message.content.startsWith(PREFIX) {
body = message.content.slice(PREFIX.length)
var args = message.content.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
case 'gw':
var gw = args.slice(1).join(' ');
var thumb = args[0];
let date = new Date();
let smalldate = date.getDate() + '/' + (date.getMonth() +1) + ' | ' + date.getHours() + ':' + date.getMinutes();
message.channel.send({
to: channelID,
message: `\n <#&${'806183931065401405'}>` + `\n` + `\n 🎉 __**Giveaway**__ 🎉`,
embed: {
color: 16580705,
footer: {
text: 'Started On : ' + smalldate,
},
thumbnail:{
url : thumb
},
title: gw,
description: 'Hosted By: ' + user,
}
});
message.delete();
}
}
});
I add some code formating for you.
bot.on('message') return only message object, you can't add some other variables.
For delete initial message, you can use message.delete()
Use Discord.js documentation :) to learn methods of libery
const Discord = require('discord.js');
const bot = new Discord.Client();
const prefix = '?';
bot.on('ready', () => {
console.log('\x1b[32m%s\x1b[0m', `${bot.user.username} is online on ${bot.guilds.cache.size} servers!`);
});
bot.on('message', async (message) => {
if (!message.content.startsWith(prefix)) return;
let args = message.content.substring(prefix.length).split(' ');
let cmd = args.shift();
switch (cmd) {
case 'gw':
let gw = args.join(' ');
let thumb = args[0];
let date = new Date();
let smallDate = date.getDate() + '/' + (date.getMonth() + 1) + ' | ' + date.getHours() + ':' + date.getMinutes();
let embed = new Discord.MessageEmbed();
embed.setDescription(`Hosted By: ${message.author}`);
embed.setColor(16580705);
embed.setFooter(`Started On : ${smallDate}`); //Better use embed.setTimestamp(), because its will convert time yo user local timezone
embed.setTitle(gw);
await message.channel.send(`\n <#&${'806183931065401405'}>` + `\n` + `\n 🎉 __**Giveaway**__ 🎉`, embed)
await message.delete()
}
});
I am developing an application with local notifications with values coming from the database. However, it is repeating the notification with the same value countless times until changing to another.
Example:
1st - "The invoice of house #1 will expire"
2nd - "The invoice of house #1 will expire"
3rd - "The invoice of house #2 will expire"
Any idea what that might be and how to fix it?
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
}
}
I think the problem is in the function that execute calculateDif();
You can also create an array of your articles that you have already notified, for example notifiedHouses = []
and check if the id is already notified using .some
calculateDif(idHouse, dateBill) {
let billDate= moment(dateBill);
var MyDate = new Date();
var MyDateString;
MyDateString = MyDate.getFullYear() + '-' + ('0' + (MyDate.getMonth()+1)).slice(-2)
+ '-' + ('0' + MyDate.getDate()).slice(-2);
let warningDate= billDate.diff(MyDateString, 'days');
if (warningDate <= 5 && !this.notifiedHouses.some( item => item.idHouse === idHouse )) {
this.localNotifications.schedule({
id: 1,
text: 'The invoice of house ' idHouse + ' will expire',
sound: null,
data: { secret: 1 }
});
const house = {idHouse: idHouse}
this.notifiedHouses.push(house);
}
}
Every time I get a new price, the following is supposed to happen:
totalprice = totalprice + cart[i]
For example, if the totalprice was previously 500 and a new price is 800, the totalprice is supposed to be (500 + 800) whereas it's currently (500 + 500 + 800). Why does this happen?
exports.add = function(req, res) {
var cart = req.body.cart;
console.log('frome node..adding checkcart.js');
console.log("Session Initialized!!");
for(var i = 0 ; i < cart.length ; i++) {
totalprice = cart[i].price + totalprice;
console.log('Current Price: '+cart[i].price);
}
req.session.cart = cart;
console.log(cart);
console.log('total: ' + totalprice);
//req.session.totalprice = totalprice;
json_responses = {
"totalprice": req.session.totalprice
}
res.send(json_responses);
};
This is one of many answers. I would suggest creating a variable that will count the amount of items already added. Otherwise, your for loop will keep counting them all again and again. Bare in mind your question lacks a lot of code, so this will have me add two options.
Option 1
Every time a user adds an item the add function will be called. For this option all you have to do is add the last added item to the total price calculation. So in your code, instead of:
for(var i = 0 ; i < cart.length ; i++) {
totalprice = cart[i].price + totalprice;
console.log('Current Price: '+cart[i].price);
}
Use:
totalprice = cart[cart.length-1].price + totalprice;
Option 2
This option is for when a user can add many items, and the prices are calculated once the user clicks a button that calls the add method. This is just slightly more tricky. You need to add a counter that will count the items already calculated. So in code:
var counter = 0;
exports.add = function(req, res) {
var cart = req.body.cart;
var prevCounter = counter;
counter = req.body.cart.length - counter; // items added in the session
console.log('frome node..adding checkcart.js');
console.log("Session Initialized!!");
for(var i = prevCounter ; i < counter ; i++) {
totalprice = cart[i].price + totalprice;
console.log('Current Price: ' + cart[i].price);
}
req.session.cart = cart;
console.log(cart);
console.log('total: ' + totalprice);
//req.session.totalprice = totalprice;
json_responses = {
"totalprice": req.session.totalprice
}
res.send(json_responses);
};
Good luck !