0

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&apos;t have any messages yet
    </Text>
  );
};

And in my terminal, this is the output:

enter image description here

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.

1
  • Can you elaborate what is the userExternalId type, doesn't look like an array though. Commented Dec 22, 2021 at 11:47

1 Answer 1

1

Array is always call by reference. When you console all three,

  1. messages was initially empty array// call by reference
  2. thus messages.length was 0 //call by value
  3. thus messages[0] was undefined. //call by value

But since console.log(messages) is call by reference, it later gets updated to the correct data, but the other 2 consoles are not updated.

Looks like the messages array that you are passing is coming from an asynchronous call, try to use async await and only call the function when the messages data has come.

Sign up to request clarification or add additional context in comments.

3 Comments

Hi, thanks for the comment. So the messages data comes from my database. I use a useFocusEffect on one screen that fetches this data, this is a promise. What doesn't make sense though is I have the exact same approach in a different part of my app that works fine.
Can you add the code of that part from where you are doing this api call and calling this function? Maybe that can help in finding the issue.
I have added the code above, the getMessages() function simply queries the database, and returns an Message[]. It is asynchronous.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.