As part of the project I'm developing with React, I'm trying to render out the status of a radio button by referencing the id's of two lists of objects to pattern match and return a Boolean value, which is then assigned to said Radio button. I think the limitation here is my JavaScript knowledge as, as far as I can tell, the logic follows. For context, the lists being compared are a list of all of the possible applications a user can have, and then the list of applications a user does have. My goal is to render the status of a radio button based on those that match. Below are some code snippets of the execution.
The JSX of my component being rendered
{applications.map((app: Application) => (
<FormControlLabel key={app.id} control={
<Radio
checked={userHasApplicationCheck(app.id)}
onClick={handleRadioChange}
value="a"
name="radio-buttons"
inputProps={{ 'aria-label': app.id }}
/>} label={app.id} />
))}
The JavaScript function it references when evaluating whether a radio button should be checked or not.
Note: props is a User object which has a list of owned applications being referenced by props.applications
function userHasApplicationCheck(id: string) {
props.applications.forEach((app: Application) => {
if (app.id === id) {
console.log(`User has this app: ${app.id}`);
return true
}
else { return false }
})
return false
}
The issue I'm having is that none of my radio buttons are rendered checked at all, despite my console log statements confirming the status correctly into the terminal. It's likely I've just done something silly syntactically but I can't see it.
Solution
Thanks to the comment by @Rithick, I now know that returning a boolean value inside of a For Each loop doesn't exit the loop. As such I modified my approach to the following:
function userHasApplicationCheck(id: string) {
let found = false;
props.user.applications.forEach((app: Application) => {
if (app.id == id){
found=true;
}
})
return found;
}
Have since tested this and can confirm it's working.
CodePudding user response:
Return Statement inside forEach method doesn't terminate that function because here we pass each element to a callback function. So that callback function returns not the forEach method. So it continues to call that callback function for the rest of the elements in the array. That's why your function after completing that forEach method goes to the last statement & return false. Solution: Instead of forEach method prefer to use regular for..of & for..in loop when you want to terminate a loop in middle.