I am having trouble with something that seems ridiculously simple and I can't believe I have had to result to this.
I have an array messages: Message[] = [...] that I need to iterate through. However, the loop/mapping is not happening. I have tried all kinds of iteration that I know of, yet none seem to work.
Here is my code:
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>
);
};
And in my terminal, this is the output:
So as you can see, when I log messages, it correctly outputs the data, but if I try and check the length, or access an element, it doesn't work.
EDIT
Here is where I make the call to my database to get the messages data.
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])
);
Appreciate anyone that can help, thanks.
