How to get week no from a date like moment("31/01/2022") should return 6.
Category: javascript
Category Added in a WPeMatico Campaign
Fresh installation by npx react-native init myapp causes in Error
@if condition not working in scss when passing dynamic value from html?
In my html file i am passing value for –is-item-status as :-
<ion-label class="textColor label-md black-shade-light" style="--is-item-status: {{item.status}}" >{{item.status | formatEnum | async}}</ion-label>
(Note:- this is populated inside *ngFor condition).
in the browser i am able to see the value getting populated as :-
element.style{ --is-item-status: INVOICE_OPEN }
In my scss file i have code like :-
.textColor {
@if var(--is-item-status) == 'INVOICE_OPEN' {
color: blue;
} @else if var(--is-item-status) == ('PAYMENT_STATUS_CANCELLED' or 'INVOICE_CANCELLED' or 'ORDER_CANCELLED') {
color: red;
} @else if var(--is-item-status) == ('PAYMENT_STATUS_PARTLY_APPLIED' or 'INVOICE_PARTLY_PAID' or 'ORDER_CLOSED') {
color: black;
} @else if var(--is-item-status) == ('PAYMENT_STATUS_APPLIED' or 'INVOICE_PARTLY_PAID' or 'ORDER_INVOICED') {
color: green;
} @else {
color: yellow;
}
}
But the if conditions are not getting satisfied. Could someone tell me what am i doing wrong in this ?
Property ‘userAgentData’ does not exist on type ‘Navigator’
Want to same attribute on multiple place in moongoose
{
username:{
type: String,
max: 12,
min: 4,
default: "Instagram User"
},
userId:{
type: String,
unique: true
},
email:{
type: String,
unique:true
},
password:{
type: String,
min:6,
select: false
},
dob:{
type: String,
required: true
},
profilePic:{
type:String,
default:"/image/avatar.jpg"
},
follower:[{
followerId:{
type:String,
},
followerName:{
type:String,
},
followerPic:{
type:String,
}
}],
following:[{
followingId:{
type:String,
default: "__I want same objectId here__"
},
followingName:{
type:String,
default:"**Same username here**"
},
followingPic:{
type:String,
default:"**same profile pic here**"
}
}],
}
Find path of object property, recursively
I want to print path of object key, dynamically. Here is my code:
const Tree = ({ data }) => {
let path = "onboarding";
return Object.keys(data).map((key) => {
if (Array.isArray(data[key])) {
path = path + "." + key;
return (
<Tree data={data[key]}></Tree>
);
}
if (typeof data[key] === "object") {
path = path + "." + key;
return (
<Tree data={data[key]}></Tree>
);
} else {
path = path + "." + key;
return (
<input defaultValue={data[key]}
style={{ fontWeight: "bold" }}
disabled={!this.props.isEditable}/>
);
}
});
};
and its my data
onboarding: {
enumType: 1,
key: "key1",
steps: [
{
title: "STEP ONE",
description: "des1",
instructions: [
{
icon: "step_power",
label: {
text: "text1",
color: "A11111",
location: "top",
},
},
],
},
{
title: "STEP TWO",
description: "des2",
instructions: [
{
icon: "step_power",
label: {
text: "text2",
color: "A11111",
location: "top",
},
},
],
}
And i want to print path of key for each iteration, expected output :
- “onboarding.enumType”
- “onboarding.key”
- “onbording.steps”
- “onboarding.steps[0]”
- “onboarding.steps[0].title”
- . . .
- “onboarding.steps[1].instructions[0].label.location”
unexpected identifier while compiling ejs
I get the titled error when trying to compile the following
<table>
<tr >
<th>First Name</th>
<th>E-mail</th>
<th>Last LogIn</th>
</tr>
<% for(var i=0; i < users.length; i++) { %>
<tr>
<td><%= users[i].name.trim() %></td>
<td><%= users[i].email.trim() %></td>
<% if users[i].lastLogIn.trim() !== null %>
<td><%= users[i].lastLogIn.trim() %></td>
<% else %>
<td><0></td>
<% endif %>
</tr>
<% } %>
</table>
can i get help please
Counting animation Not displaying decimal values
This is the code i have used, i am getting an issue that its not displaying decimal values
i.e : if i give the value 4.5 , it displays only 4, please help me with the problem
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 8000,
easing: 'swing',
step: function (now) {
// $(this).text(Math.ceil(now));
$(this).text(Math.ceil(now).toString().replace(/(d)(?=(ddd)+(?!d))/g, "$1,"));
}
});
});
Detecting inactive users and resetting login time
- I’m trying to extend the login time by detecting inactive users.
- Can the above function be implemented using local storage?
- When the user clicks, scrolls, moves, and inputs the keyboard, they try to reset the login time.
- I’m using javascrip
Return to a specific component/ div in a page when coming from a specific page in React JS (Without anchor tag)
I am working in an application where in a page it have a button. When I select the button it will go to another page.
I am using Push in UseHistory() to pass between pages. I know we can go to a specific div using anchor tag. But I don’t want to use anchor tag. Can anyone help me how can I do that in react.
This is the button component I used to redirect to another page.
const { push } = useHistory();
return (
<>
{surveyDisableTime && <SurveyInfoBox />}
<EmptyList
image={<NoDataIcon />}
title={formatMessage({ id: 'event.survey_response.assign_survey.heading' })}
subtitle={formatMessage({ id: 'event.survey_response.assign_survey.subheading' })}
onButtonClick={() => push(AppRoute.editEvent.replace(':eventId', event.id), { from: pathname })}
buttonText={formatMessage({ id: 'event.survey_response.assign_survey.button_label' })}
disabled={surveyDisableTime}
/>
</>
);
This is the onclick function -> onButtonClick={() => push(AppRoute.editEvent.replace(':eventId', event.id), { from: pathname })}
In the editEvent I need to go to a specific component. How can I do that?
Thankyou in advance.
Combining Objects based the first two keys and summing values
I currently have an array of objects that looks similar to this where the dates are out of order and each object has the same keys:
const mainArray = [
{Name: John Doe, Date: 1/1/22, Water: 5, Chips: 4, Pizza: 0, HotDog: 0},
{Name: John Doe, Date: 1/5/22, Water: 0, Chips: 0, Pizza: 6, HotDog: 4},
{Name: John Doe, Date: 1/1/22, Water: 5, Chips: 0, Pizza: 0, HotDog: 2},
{Name: Max Dow, Date: 2/7/22, Water: 5, Soda: 4, Pizza: 0, HotDog: 0},
{Name: Max Dow, Date: 2/7/22, Water: 0, Soda: 4, Pizza: 2, HotDog: 1},
{Name: Max Dow, Date: 1/5/22, Water: 1, Soda: 1, Pizza: 0, HotDog: 0},
]
And I would like to combine objects if they share the same name and date. When combining those objects I am also trying to sum like key values together.
The result would look like this:
const mainArray = [
{Name: John Doe, Date: 1/1/22, Water: 10, Chips: 4, Pizza: 0, HotDog: 2},
{Name: John Doe, Date: 1/5/22, Water: 0, Chips: 0, Pizza: 6, HotDog: 4},
{Name: Max Dow, Date: 2/7/22, Water: 5, Soda: 8, Pizza: 2, HotDog: 1},
{Name: Max Dow, Date: 1/5/22, Water: 1, Soda: 1, Pizza: 0, HotDog: 0},
]
I was able to build a function that worked only if the object name and date were in order next to each other however I was unable to find a way to organize all objects by both name and date.
Thank you for your time and effort!
react showing 2 same outcome
i am trying to send a prompt a notification when my sensor hit the threshold. but instead of 1 prompt, i receive 2 of the same prompt.
const TempGraph = () => {
const [data, setData] = useState([]); // sound , temp, humidity , light , motion .
const [thresholddata,setThresholdData] = useState([]);
var result = [];
// var i = 0;
//const thresholds = '35';
function addZero(i) {
if (i < 10) {i = "0" + i}
return i;
}
useEffect(() => {
const interval = setInterval(() => asyncFetch(),5000) //5000ms = 5sec
return () => clearInterval(interval) // clear the interval everytime
}, []);
/* fetch specific sensor type */
const asyncFetch = async() => {
await fetch('api')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => {
console.log('fetch data failed', error);
});
//fetching threshold data
await fetch('api')
.then((response) => response.json())
.then((json)=>setThresholdData(json))
.catch((error) => {
console.log('fetch threshold data failed',error);
});
};
if(data.length != 0){
/* Loop through threshold table to get the same type id */
for(var x =0;x<thresholddata.length;x++){
// console.log(thresholddata[i])
if(thresholddata[x].typeid == data[data.length-1].typeid && thresholddata[x].sensorid == data[data.length-1].sensorid){
result = thresholddata[x];
console.log(result)
}
}
/* notification when the data value is over the threshold */
if(result.upperthreshold < data[data.length-1].value){
openNotificationWithIcon('warning',data[data.length-1].location);
}
}
/* graph here */
}
I used a for loop to loop through all the data and make sure the id of them are the same. and when the value of the sensors hits above the threshold it will go to the notification. but the result variable saved 2 same value.
Rerender DOM without using internal state of react and without using DOM manipulation
import React, { StrictMode} from "react";
import ReactDOM from "react-dom";
const rootElement = document.getElementById("root");
function App({store, action}) {
return <>
<h1>{store.counter}</h1>
<button onClick={() => action(true, store)}>
increment
</button>
<button onClick={() => action(false, store)}>
decrement
</button>
</>
}
const store = {
counter: 0
}
const action = (bool, state) => {
state.counter = bool ? store.counter + 1 : store.counter - 1
}
ReactDOM.render(
<StrictMode>
<App store={store} action={action}/>
</StrictMode>,
rootElement
);
Without changing App function , store and action we have to update the value on DOM .
one solution that I know is : Adding **setInterval function , but this is not most optimized solution .
setInterval(()=>
ReactDOM.render(
<StrictMode>
<App store={store} action={action} />
</StrictMode>
);
,10);
Here is the codepen example for the same :
Codepen
How to cast a plain json object to typeorm entity
There is a transformer class called PlainObjectToNewEntityTransformer, if I need to invoke its transform function, I have to pass in the EntityMetadata which requires connection, I think casting doesn’t really need connection. The current workaround is to do the following by just assign in constructor, but this won’t preserve the schema since the field keys are often changed.
@Entity('myentities')
export class MyEntity {
constructor(partial?: Partial<MyEntity>) {
if (partial) {
Object.assign(this, partial);
}
}
}
const entity = new MyEntity(json);
I am not sure if the casting can be done in a proper way.
Which is less performant? defining and calling a default blank function vs type checking if the function exists before calling it
Which is more performant? I prefer the first one as it’s more pleasing to read vs the second one. Even if it’s a minuscule amount of performance gain which is better?
function(callback = () => {}) {
callback();
}
vs:
function(callback) {
if (typeof callback === 'function') {
callback()
}
}



