array mapping not returning value react - javascript

I have the following function
churnModel = () => {
if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
return("N/A")
} else {
this.props.churnModel.map((churn) => {
if (churn === undefined || churn.length === 0) {
return("N/A")
} else {
return(churn.map((model) => {
this.service(model.scoreModelId)
}))
}
})
}
};
The this.service functions looks like this...
service(e) {
switch(e.toString().toLowerCase()) {
case "in":
return <span>in</span>
case "rpt_callr":
return <span>repeat</span>
default:
return <span>na</span>
}
}
I am expecting to display the result in here:
<div className="riskScore">{this.churnModel()}</div>
Nothing gets displayed, but when I put in logs, those get printed.
What is happening here?

you need to put return before this.props.churnModel.map.this.service(model.scoreModelId)
A function will return undefined if nothing is nothing is returned.
map() takes a callback and changes each element of array to return value of the that callback. If you don't return anything all elements will be undefined
You can also get rid of return before this.service(model.scoreModelId) by removing {}.Like this.
return(churn.map((model) => this.service(model.scoreModelId)))
Here is the code
churnModel = () => {
if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
return("N/A")
} else {
return this.props.churnModel.map((churn) => {
if (churn === undefined || churn.length === 0) {
return("N/A")
} else {
return(churn.map((model) => {
return this.service(model.scoreModelId)
}))
}
})
}
};

You have to use return statement in couple of lines:
churnModel = () => {
if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
return("N/A")
} else {
return this.props.churnModel.map((churn) => {
if (churn === undefined || churn.length === 0) {
return("N/A")
} else {
return(churn.map((model) => {
return this.service(model.scoreModelId)
}))
}
})
}
};
Why do you need return? It's because you're using curly braces.

Related

Why does this function return undefined but console.logs the correct answer?

I have this function
const getMonthlyPriceFromData = (planName) => {
planTypeData.map((item) => {
if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
return item.monthlyFee;
}
return null;
});
};
when I console.log(item.monthyFee) it returns the correct answer but when I call
console.log(getMonthlyPriceFromData('Free')) it returns undefined?
There is no actual return statement inside your function:
const getMonthlyPriceFromData = (planName) => {
return planTypeData.map((item) => {
if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
return item.monthlyFee;
}
return null;
});
};
Or use short arrow form. This way you can omit the return keyword, only if you skip the curly braces too {:
const getMonthlyPriceFromData = (planName) => planTypeData.map((item) => {
if (item.name === planName) {
console.log(item.monthlyFee, 'fee')
return item.monthlyFee;
}
return null;
})
EDIT:
OP seems to want only one item retuned from the array and for that find() would be a better approach:
const getMonthlyPriceFromData = (planName) => planTypeData.find((item) => {
if (item.name === planName) { console.log(item.monthlyFee, 'fee')
return true; }
return false; })
You need to add a "return" before "planTypeData.map", like this:
const getMonthlyPriceFromData = (planName) => {
return planTypeData.map((item) => {
if (item.name === planName) {
return item.monthlyFee;
}
return null;
});
};
console.log(getMonthlyPriceFromData('Free'))
Then it should work!

Value below evaluate just now error with console.log

can someone help me solve this problem. I dont understand why console log and value of it after evaluate different. As you can see this pic below key SeqNo in console.log has no value but it actually has it
This is my function in component in Angular will return array and will be parameter for other function has above console.log
async prepareDetailForSave(allModelSalesTargetDetail) {
const salesTargetDetailForSave: any = [];
for (const detail of allModelSalesTargetDetail) {
await new Promise ((resolve, reject) => {
if (detail.SeqNo === '') {
if (detail.Money !== 0) {
detail.RSeqNo = this.objMaster.SeqNo;
detail.CreateDate = UtilsService.getCurrentDate();
detail.ModifiedDate = UtilsService.getCurrentDate();
if (this.global.connectionStatus === 'offline') {
detail.SeqNo = UtilsService.getLocalSeqno().toString();
} else {
this.jamService.getInvoiceCode('sales-target-detail').subscribe((res: any) => {
detail.SeqNo = res['seqno'];
});
}
salesTargetDetailForSave.push(detail);
}
} else {
salesTargetDetailForSave.push(detail);
}
resolve();
});
}
return salesTargetDetailForSave;
}

properties are undefined inside of promises

This is my typescript function where I'm trying to use a promise:
public onEditSubmit() {
const model = this._sharedService.createUpdateModel(
null,
this.editForm
) as LOG;
model.fileId = this.fileId;
model.startEffectiveDate = Shared.toISODate(model.startEffectiveDate);
model.endEffectiveDate = Shared.toISODate(model.endEffectiveDate);
let deferredExecutionCheck = new Promise((resolve, reject) => {
this._updateService
.getAllById(this.selectedItem.LogId)
.subscribe(
r => {
this.records = r;
this.records.forEach(element => {
if (
element.StatusId === 1 ||
element.StatusId === 2 ||
element.StatusId === 4 ||
element.StatusId === 5
) {
this._notificationService.showErrorMessage(
`MESSAGE GOES HERE`,
"IN PROGRESS"
);
reject("In Progress");
}
});
resolve("Not In Progress");
},
e => {
throw e;
}
);
console.log("finished");
});
let originalEditSubmit = function(result: any) {
if (this.editMode === "Add") {
this.add(model);
} else {
if (
(model.wfStatusId === Status.Review ||
model.wfStatusId === Status.LoadFailed ||
model.wfStatusId === Status.Completed) &&
model.eventStatusId === eStatus.Cancelled
) {
this._confirmDlg.closable = false;
this._confSvc.confirm({
accept: () => {
model.cancelRcdb = true;
this.update(model);
},
message: "Cancel RCdB Dataset?",
reject: () => {
model.cancelRcdb = false;
this.update(model);
}
});
} else {
this.update(model);
}
}
};
deferredExecutionCheck.then(
result => originalEditSubmit(result),
error => console.log("error", error)
);
}
Error: Uncaught (in promise): TypeError: Cannot read property
'editMode' of undefined TypeError: Cannot read property 'editMode' of
undefined at originalEditSubmit
I moved the this.fileId property outside of the originalEditSumbmit method and it now is being read. But now it seems like this.editMode is now having the same issue.
Can I not have these properties inside of my promises like this?
change
let originalEditSubmit = function(result: any) {
to
let originalEditSubmit = (result: any) => {

How to properly format nested try/catch blocks inside a function that returns a server response

I have a function that is called that must return a response to a server. Inside this function are two await function calls that are nested. To track error handling, I added try/catch blocks. Is there a way to avoid having nested try catch blocks to track all cases where the function might fail so I can send back an error server response?
Here's my function, it queries for a user's unique device id's and sends a push notification to each one. If a token becomes invalid, then I delete it from my database:
function findUserDevices(uid: string, message) {
collectionData(fb.firestore().collection('devices').where('userId', '==', uid)).pipe(
filter((userDevices) => userDevices && userDevices.length > 0),
take(1)
).subscribe( async (devices: any) => {
var userDeviceTokens: string[] = devices.map((device: any) => device.token);
if (userDeviceTokens !== undefined && userDeviceTokens.length != 0) {
try {
message['tokens'] = userDeviceTokens;
const pushResponse = await admin.messsaging().sendMulticast(message);
if (pushResponse.failureCount > 0) {
const failedTokens = [];
pushResponse.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(userDeviceTokens[idx]);
}
});
failedTokens.forEach( async (token) => {
var tokenInstanceID = token.split(':')[0];
try {
await deleteOldToken(tokenInstanceID);
console.log(`Token ${tokenInstanceID} deleted`)
} catch {
return res.status(500).send("err");
}
})
return res.status(200).send("ok");
} else {
return res.status(200).send("ok");
}
} catch {
return res.status(500).send("err");
}
} else {
return res.status(200).send("ok");
}
})
}
It just feels a bit excessive with all the returns I must have. Where can I improve?
EDIT, broke apart code into three blocks to prevent arrow coding
function findUserDevices(uid: string, message) {
collectionData(fb.firestore().collection('devices').where('userId', '==', uid)).pipe(
filter((userDevices) => userDevices && userDevices.length > 0),
take(1)
).subscribe(async (devices: any) => {
var userDeviceTokens: string[] = devices.map((device: any) => device.token);
if (userDeviceTokens !== undefined && userDeviceTokens.length != 0) {
try {
message['tokens'] = userDeviceTokens;
const response = await admin.messaging().sendMulticast(message);
const oldTokensArray = checkOldTokens(response, userDeviceTokens);
if (oldTokensArray.length > 0) {
await deleteOldTokens(oldTokensArray);
return res.status(200).send("ok");
} else {
return res.status(200).send("ok");
}
} catch (err) {
return res.status(500).send(err);
}
} else {
return res.status(200).send("ok");
}
})
}
function checkOldTokens(response, userDeviceTokens) {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(userDeviceTokens[idx]);
}
});
return failedTokens;
} else {
return [];
}
}
async function deleteOldTokens(tokenArray) {
for (const token of tokenArray) {
await fb.firestore().collection('devices').doc(token).delete();
}
}

AWS Javascript SDK Function return

Hello how can I write the following code so that there is no race condition if I return inside the get() function it only returns from that function but if I return from the outer function it prematurely returns.
function checkifvalid (userIdPassed) {
// code to be executed
var params43 = {
TableName: 'users',
Key: {
'pid': req.user.iden
}
}
var returnVal = null
docClient.get(params43, function (err43, data43) {
if (err43) {
return res.json({'errasdsd342sd': 'erhf32623hrf'})
} else {
if (data43.Item.useract && data43.Item.curadmin != '0') {
returnVal = true
} else {
returnVal = false
}
}})
if (returnVal !== null) {
return returnVal
}
}

Categories

Resources