I have a function which checks if comments author is current or not.This function returns true or false.
I also have function which checks result of this function and the problem is result function always returns true.
Any suggestions please?
const checkCommentAuthor = (): boolean => {
return comments.filter((item: any): boolean => {
if (item.username === localStorage.getItem("username")) {
return true;
} else {
return false;
}
});
};
const checkCommentAuthorResult = (): any => {
let checkResult = checkCommentAuthor();
if (checkResult) {
return <IsCommentAuthor / > ;
} else {
return <IsNotCommentAuthor / > ;
}
};
return checkCommentAuthorResult();
};
item.usernameis undefined andlocalStorage.getItem("username")is also undefinedfilter(), which means your comments array changes into a smaller array. So if you have five comments, and two are by the author, the function returns an array of two comments, not true or false. An array is truthy, so it always returns true. I'm also wondering how exactly this is supposed to work in general: shouldn't you check whether the user is the author for each comment individually?let checkResult = checkCommentAuthor()[0]