Checking two variables on condition from localStorage: - javascript

Is there a way to check to variable in localstorage ?
Storage {user: 'undefined', new: '{"_id":"61dd228336a3923d2286b994","email":"ahmadsa…","updatedAt":"2022-01-11T06:24:03.675Z","__v":0}', lscache-localhost:preview:v20180702-cacheexpiration: '27376332', lscache-localhost:preview:v20180702: '{}', length: 4}
And sometimes the data may be on the user property base on user login . below is the login that returns the property in user
Storage {user: '{"team_members":{"memberFullname1":"memberFullname…","updatedAt":"2022-01-10T01:43:30.288Z","__v":0}', new: 'null', length: 2}
How can I create condition that checks both property an only return the ones that contain a value ?
Base on user log in, I can only use one variable either new or user. Is there not away I can check two conditions before rendering my data from localStorage ?
This is the Method I try. But it only check the first condition even though the second condition is there, it return. Uncaught error in Json.parse()
if (typeof Storage !== "undefined") {
if (localStorage.getItem("new")) {
setUser(JSON.parse(window.localStorage.getItem("new")));
} else if (localStorage.getItem("user")) {
setUser(JSON.parse(window.localStorage.getItem("user")));
}
return;
}
Is there a way I can check both condition ? Your time is really appreciated. please I am a brother need..
And lastly how can I prevent re-rendering of the state

If user undefined, do new, if that's undefined, do {}, parse.
if (typeof Storage !== "undefined") {
setUser(JSON.parse(localStorage.user || localStorage.new || '{}'));
}
Though, if you look at new, it's not the same as user, in terms of structure so you might want to fix that else they are not the same thing.

I found these code allows me to check both conditions and it didn't return error like the previous one.
useEffect(() => {
const fetchStates = async () => {
const result = await axios(
"https://nigerian-states-info.herokuapp.com/api/v1/states"
);
setStates(result.data.data);
};
fetchStates();
if (localStorage.user === "undefined") {
return setUser(JSON.parse(localStorage.getItem("new")));
} else if (localStorage.new === "undefined") {
return setUser(JSON.parse(localStorage.getItem("user")));
}
}, [formData, user]);
Finally after a bunch of try and error, I finally arrived at that part. I want to sent my sincere appreciation to all those who took there time and review my issues even those that did not get to answer. I send A BIG THANK YOU especially to lawrence cherone your idea was a great helpful in shaping my thought. thank you all

Related

Awaiting code until filter is finished - Nextjs/Javascript

I am looking on how to make my code after my filter function await the results of my filter function to complete before running. However I am not sure how to do this.
My filter function takes in another function (useLocalCompare) which causes the execution of my filter function to be a little longer than normal, which then leads to my next piece of code (that depends on the results of my filter function) executing before my filter function is complete.....which leads to undefined.
Is there anything similar to a callback I can use to force my subsequent piece of code to wait till the filter is finished?
Relevant code is written below.
if (flatarrayofvalues !== null && genre !== null) {
const filtteredarray = await flatarrayofvalues.filter(
(placeholder) => {
if (useLocalCompare(genre, placeholder.name) == true) {
console.log("HURAY!!!!", placeholder.id, placeholder.name);
placeholder.name == placeholder.name;
}
}
);
console.log("MY FILTERED ARRAY IS", filtteredarray);
console.log("The ID FOR MY MY FILERED ARRAY IS two ID", filtteredarray[0]?.id);
return filtteredarray[0].id;
}
}
}
For those curious, useLocalCompare basically checks to see if the genre parameter pulled down from the URL is the same as a name parameter from the array I am filtering. Reason I have this is due to people having different case sensitivity when putting in URLS. EX: it will pull down "HORrOR" and match it to the object name in the array I am filtering called "horror". I then extract the ID from that object.
you have to return the conditional from filter as it is "explicit return"
const filtteredarray = await flatarrayofvalues.filter(
(placeholder) => {
if (useLocalCompare(genre, placeholder.name) == true) {
console.log("HURAY!!!!", placeholder.id, placeholder.name);
return placeholder.name == placeholder.name; // here
// why not just return true ?? instead of above line
}return false
}
);
Also I'm not sure this makes sense
placeholder.name == placeholder.name; you mean just return true; ?

Why is the condition in this callback always returns false?

I have a home SPA based on Vue. One of the components is driven by a v-if="isDisplayed".
This isDisplayed is set by listening to a MQTT topic (see footnote) and new messages received are handled by the following function (I sepcifically used 'hello' instead of false to make sure the switch goes there). The topic of interest is display_school_edt.
mqttMessage(topic, message) {
console.log(`App.vue received topic ${topic} with payload '${message}'`)
if (topic === "dash/reload") {
window.location.href = window.location.href
document.location.reload(true);
}
if (topic === "dash/darkmode") {
this.nightmode = JSON.parse(message) ? "night" : "day";
}
// this is the part I have problems with, I left everything for completness
if (topic === "display_school_edt") {
console.log(`edt display received: '${message}'`);
if (message === 'on') {
this.isEdtDisplayed = true
} else {
this.isEdtDisplayed = 'hello'
}
// I initially went for the ternary below - same results
// message === "on" ? this.isEdtDisplayed = true : this.isEdtDisplayed = 'hello';
console.log(`new edt display: ${this.isEdtDisplayed}`);
}
}
When I publish to the monitored topic display_school_edt (twice: one the message is on and the other time off), here is what I get on the console:
In other words, no matter if on or off is received, the condition is always false.
There is something obviously wrong with my code but the more I look, the better it looks.
Footnote: the fact that it is that specific protocol does not matter (it is a kind of bus often used with IoTs), you can assume that somehow mqttMessage() is executed with the parameters topic and message that are both strings.
This is indeed unexpected if message is of type string. However, it probably is not, and the only times you output message, you actually coerce it to string. So if you see from a previous output that it coerces to "no", then in the if condition you should do the same, and force that conversion to string:
if (message+'' === 'no')
NB: This will call message.toString(), just like it does when you reference it within a template literal as ${message}.

Discord.js - Getting users last activity?

I'm trying to find out if its possible to get the time/information of users last activity retrospectively using discord.js
Say I have something like
client.guilds.find('id', 'SERVER ID').fetchMembers().then(members => {
const role = members.roles.find('name', 'Newbies')
role.members.forEach(member => {
console.log(member.user.lastMessage) // null
})
})
Unless the member has posted, since the client is listening, the lastMessage is always null.
Is there a way to find the last activity? or a workaround, like a query to return all the users messages, which I can then take the most recent one from?
Effectively I want to know what date/time the user last posted so we can monitor non-contributing accounts.
Thanks
After looking thought the documentation I didn't find something neither so I came up with a manual search function.
Basically, it will scan every channels until finding a message from X user, or the end of the messages in the channel. It then compare the last messages of the users from every channels and print the last one.
It can be very long if the user hasn't write since a long time. Of course, you have to check lastMessage before trying this.
I would add a time limit maybe. Because if you have thousand of messages, the function will run eternally.
You can stop the function if the last message found is in the accepted time to not be kick/do whatever.
I made the search stop if the first message found in the pack of fetched messaged is older than the ban limit, however, if the first message is not older, remember that it means for the other, so we still need to check them (it can be avoided by checking the last message of the pack as well).
async function fetchMessageUser(chan, id, res) {
let option = {};
if (typeof res !== 'undefined'){
option = {before: res.id};
}
return await chan.fetchMessages(option)
.then(async msgs => {
if (msgs.size === 0){
return {continue: false, found: false};
};
if ((Date.now() - (msgs.first().createdTimestamp)) > 86400000 ) { // 1 day
return {continue: false, found: false};
}
let msgByAuthor = msgs.find(msg => {
return msg.author.id === id;
});
if (msgByAuthor === null){
return {continue: true, id: msgs.last().id};
} else {
return {continue: false, found: true, timestamp: msgByAuthor.createdTimestamp};
}
})
.catch(err => console.log('ERR>>', err));
}
client.on('message', async (msg) => {
let timestamp = [];
for (let [id, chan] of msg.guild.channels){
if (chan.type !== 'text'){ continue; }
let id = '587692527826763788'; // id of the user, here a non verified account
let res;
do {
res = await fetchMessageUser(chan, id, res);
} while(res.continue);
if (res.found) {
timestamp.push(res.timestamp);
}
}
console.log(timestamp);
let first = timestamp.sort((a,b) => (b-a))[0];
console.log(new Date(first));
});
A better variant would be to run it for an array of users, checking all 50 last messages from every channel, and associating each users with his most recent messages if he wrote one, and doing this until all the messages in all the channels are too old to avoid a kick/whatever. And then do something for all the users who don't have an associated messages.
I think what you need is one of Discord's built in features, namely: pruning. This feature will grab inactive members and lets you kick them. Luckily, discord.js has an API call for it and even lets you get the number of members first without actually kicking them by setting the dry parameter to true. The feature will also allow you to specify the amount of days a user has to be inactive.
Have a look at the docs: https://discord.js.org/#/docs/main/stable/class/Guild?scrollTo=pruneMembers
Hope that helps out!

Javascript, how to check if object exists

I am making a script in Javascript script that gets a SQL response, then processes it. Basically, I want to check if the username value exists in result[1]. When it checks, it errors out and says that it does not exist. If it does not exist, I want it to return false, not stop the program.
Here is the code:
if (result[1].username != undefined) {
return true;
} else {
return false;
}
I have tried using typeof(result1) == undefined, but it gives me the same error.
First, you have to make sure the result exists, otherwise you'd be indexing into undefined which would crash your application.
Second, you can make that check less verbose with:
return (result[1] && result[1].username)
which will return a falsey value if it doesn't exist, and whatever the username is, if it does.
In case you need an explicit true to be what the function returns, you can coerce it:
return (result[1] && (result[1].username && true))
I would make sure to refactor for readability, but that's the gist.
You could use the in operator. For example:
let trueObj = { username: 'Foo' };
let falseObj = { };
if ('username' in trueObj) {
console.log('username found in trueObj');
} else {
console.log('username not found in trueObj')
}
if ('username' in falseObj) {
console.log('username found in falseObj');
} else {
console.log('username not found in falseObj')
}
First of all please check whether the result itself exists or not and make the corresponding & operator and i think this will definitely help
if (result && result[1] && result[1].username) {
return true;
} else {
return false;
}
But if you don't want to make your code complex then you can try lodash library.
https://lodash.com/

user authorization with equals() in javascript

I made a blog in which a user can only edit it the blogs they created. But now I want to make an admin that can edit and delete any post he wants.
if(foundBlog.author.id.equals(
req.user._id ||
foundBlog.author.username === "ADMIN"
)) {
next();
} else {
res.redirect("back");
}
But my code doesn't work.
equals() is not a valid String function except you have implemented this yourself. If you haven't and want to, you could do something as simple as
String.prototype.equals = function(str){
return this.toString() === str;
}
and then
"hello".equals("hello") // gives true
"hello".equals("kitty") // gives false
However, I would advice against poisoning the prototype of a well-known/built-in object or any shared global space for that matter cause that is a recipe for disaster.
With that said, I'll just go for the strict equality comparison.
if(foundBlog.author.id === req.user._id || foundBlog.author.username === "ADMIN")
No harm no foul.

Categories