Cannot read property 'push' of undefined typescript - arrays

I am trying to push a date object into an array and I get this error "cannot read property 'push' of undefined".
export class CalendarComponent {
days: Date[]
showMonths() {
const interval = new Interval();
interval.fromMonth = this.selectedFromMonth.number;
interval.fromYear = this.selectedFromYear.number;
interval.toMonth = this.selectedToMonth.number;
interval.toYear = this.selectedToYear.number;
for (let i = interval.fromMonth - 1; i < 11; i++) {
const day = new Date(interval.fromYear, i, 1);
this.days.push(day);
// console.log(day);
// days.push(day);
}
// console.log(day);
}
Why do I get this error if 'days' it is already an array and 'day' it is not undefined ?

You need to initialize your property. You have just set the type of it, but actually it is undefined.
days: Date[] = [];

static typing is typescript future and when you compile your code to javascript typing will gone this just a help to developer during the build time.
days: Date[] is the same you sa days and the initial value is undefined
var days;
console.log(days); // => undefined
that why you need assaign days to [] empty array before you use it
days: Date[] = [];

Related

Rendering Date from model in react

I am trying to get the date to render in a nice format. currently rendering like this
I tried
function getEndDateFromstring(){
return itinerary.endDate.split('T').slice(-1)[0]
}
then
{itinerary.name} from {getStartDateFromstring()} to {getEndDateFromstring()}
But it is throwing an error
Uncaught TypeError: Cannot read properties of undefined (reading 'split')
This looks like a scope issue, pass the itinerary to your function like below
function getEndDateFromstring(itinerary){
return itinerary.endDate.split('T').slice(-1)[0]
}
and call like
{itinerary.name} from {getStartDateFromstring(itinerary)} to {getEndDateFromstring(itinerary)}
I got it working with this
function addZeroIfOnlyOneChar(dateString){
dateString = String(dateString);
if(dateString.length < 2){
return '0' + dateString
}
return dateString
}
function getDateFromString(dateString){
const date = new Date(dateString)
const day = date.getDate();
const month = date.getMonth() + 1;
const year = date.getFullYear();
return `${addZeroIfOnlyOneChar(day)}-${addZeroIfOnlyOneChar(month)}-${year}`
}
Thanks Everyone

Getting the sum for all of the object retrieve from SharePoint API

.subscribe((dataTotal) => {
console.log(dataTotal)
this.toGetHourData=dataTotal;
const AssociateArray = []
AssociateArray.push({dataTotal : Number})
let associateSum: number = 0;
AssociateArray.forEach(a => associateSum += a.value);
console.log(associateSum);
},
This is my code. I have pushed all of the object into an array. but when i try to sum it up. the console log a NaN.
p.s: this is my first time with stackoverflow
There are a number of issues in your code
1. Incorrect type declaration
You have declared dataTotal : Number For types you need to use number not Number hence dataTotal : number
2. You are adding a type to an array!
Consider the code AssociateArray.push({dataTotal : Number}). {dataTotal : Number} is basically a type so you are pushing an empty type to the array...
3. You can use other means to sum e.g using reduce
With these in mind you can change your code to
.subscribe((dataTotal) => {
this.toGetHourData = dataTotal;
let associateSum: number = dataTotal.reduce((prev, next) => prev + next.value , 0);
console.log(associateSum);
}
.subscribe((dataTotal) => {
console.log(dataTotal)
this.toGetHourData=dataTotal;
var clean = []
var totalnum = 0;
var associateArray = dataTotal
associateArray.forEach(element => {
if (element.strTotalAssociates !== NaN) {
clean.push(element)
console.log(element)
totalnum += element.strTotalAssociates;
console.log(totalnum)
}
});
this is the answer that me and my colleague came up with and its work.

discord.js reactions TypeError: Cannot read property 'get' of undefined

So i was trying to collect reactions from an embed but im still getting this error:
var peopleReacted = embedsend.reactions.get(party).users.array();
^
TypeError: Cannot read property 'get' of undefined
at Timeout._onTimeout
Here's my code:
message.channel.send(`${boost} **GIVEAWAY** ${boost}`, embed).then(sentEmbed => {
sentEmbed.react(party)});
setTimeout(function() {
var random = 0;
var winners = [];
var inList = false;
var peopleReacted = embedsend.reactions.get(party).users.array();
I've also been trying using
sentEmbed.reactions.get or cache.get but then i get sentEmbed is not definied
One of the errors is in embedsend.reactions.get(party).users.array();, because (assuming u're in d.js version 12), you must instead use .cache, so make it embedsend.reactions.cache.get(party).users.array();
Also, var embedsend = embed; is not a message, it is an embed object. Instead, use var embedsend = message.channel.send('${boost} **GIVEAWAY** ${boost}', embed);, then it will be set to the actual message you sent, rather than the embed.

Cannot read property 'value' of undefined for this.refs.variable.value

I am new to react.
I have a input text like so
<input type="text" class="form-control" placeholder="Number Only"
value={that.state.value}
ref={"qtype3" + item.questionId}
/>
now in a method I want to get the value inputted in the textbox,so i wrote following block in the method:
const uniqueNames = Array.from(new Set(this.state.arrrefs));
if (uniqueNames.length > 0) {
for (let i = 0; i < uniqueNames.length; i++) {
var inval = uniqueNames[i];
var ans = this.refs.inval.value;
var newans = {
taskId: this.props.location.state.tskId,
userId: this.props.location.state.userid,
questionId: "",
answer: ans
};
this.state.radioObj.push(newans);
}
}
here arrrefs is an array in the state with refs of several textboxes. In the variable inval I am getting the first value of the arrrefs. but i am getting the exception in the line var ans = this.refs.inval.value;
TypeError: Cannot read property 'value' of undefined
If I pass a hardcode value in line this.refs.inval.value instead of inval I am getting response.
for example, my uniqueNames = ["qtype3800316", "qtype3800317", "qtype3800318", "qtype3800324"]
so i want this.refs.qtype3800316.value
What am I doing wrong here?
Try using the [] operators if you want to access within an array/object by a variable.
this.refs[inval].value
Try just with: this.refs.inval
Also you can console.log(this.refs) and check what you have there.

Cannot set a property "year" of undefined TypeScript-Array

I have the following declaration in my component:
private years: Array<{
year: string,
colspan: number
}> = [];
Which is supposed to be a years-Array where each entry has the two properties year and colspan. Now I want to modify this variable with the following method called in my ngOnInit:
fillYearsArray = () => {
var currentIndex : number = 1;
//fill the first entry and do not change it afterwards, error occurs here
this.years[0].year = "";
this.years[0].colspan= 1;
this.items.forEach( (item) => {
//if the first entry.year is empty fill it with the year of the current object
if (this.years[currentIndex].year) {
//if it is already set and the years equal enlarge colspan
//otherwise go to the next entry with the "new" year
if (this.years[currentIndex].year === String(item.year)) {
this.years[currentIndex].colspan += this.columnKeys.length;
} else {
currentIndex++;
this.years[currentIndex].year = String(item.year);
this.years[currentIndex].colspan = this.columnKeys.length;
}
} else {
this.years[currentIndex].year = String(item.year);
}
});
}
But when running ng serve I get the following output:
AppComponent.html:1 ERROR TypeError: Cannot set property 'year' of undefined
at TabularComponent.fillYearsArray (tabular.component.ts:27)
at TabularComponent.push../src/app/tabular/tabular.component.ts.TabularComponent.ngOnInit (tabular.component.ts:22)
at checkAndUpdateDirectiveInline (core.js:18537)
at checkAndUpdateNodeInline (core.js:19801)
at checkAndUpdateNode (core.js:19763)
at debugCheckAndUpdateNode (core.js:20397)
at debugCheckDirectivesFn (core.js:20357)
at Object.eval [as updateDirectives] (AppComponent.html:1)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:20349)
at checkAndUpdateView (core.js:19745)
So it looks like the first object in the array would be undefined, but shouldn't TS know, that it has an property year that is changed for the object at the first entry of my years-array?
You need to add an element before you change it's value
you try to access
this.years[0]
but this.years length is 0
so you need to do it like this
this.years.push({ year: "", colspan: 1});
if you want to add item in your array you need to use the .push() function.
If you try to go to the index you want to set, it won't work

Resources