I am struggling with what appears to be a simple issue, and it's frustrating that I've had to seek help for this.
The problem lies in iterating through an array messages: Message[] = [...]
. No matter what method of iteration I try, it doesn't seem to work as expected.
Here is the snippet of code causing me trouble:
const getMessages = (messages: Message[]) => {
const cards = []
// eslint-disable-next-line no-console
console.log("Test 1: ", messages);
// eslint-disable-next-line no-console
console.log("Test 2: ", messages.length);
// eslint-disable-next-line no-console
console.log("Test 3: ", messages[0]);
let i = 0;
for (const msg of messages) {
// eslint-disable-next-line no-console
console.log("ADD TO LIST");
cards.push(
<MessageSummary
key={i}
council={msg.council}
latestMessage={msg.content}
date={msg.date"}
hasBeenRead={false}
/>
);
i += 1;
};
if (cards.length > 0) {
return messages;
}
return (
<Text style={styles.noApplicationsMessage}>
You don't have any messages yet
</Text>
);
};
The terminal output reveals that although logging messages
gives correct data, attempting to check its length or access elements poses an issue.
EDIT
Below is where I fetch the messages
from the database:
const processNewMessages = useCallback((newMessages: Message[]) => {
setMessages(newMessages);
}, []);
useFocusEffect(
useCallback(() => {
if (userExternalId < 0) {
return;
}
setLoading(true);
getMessages(userExternalId)
.then((messagesQuery) => processNewMessages(messagesQuery))
.catch(() => {
setError("Messages could not be fetched. Please try again later.");
setShowBanner(true);
})
.finally(() => {
setLoading(false);
});
}, [processNewMessages, userExternalId])
);
Your assistance in resolving this matter would be greatly appreciated. Thank you.