Even though there is data stored in the array, the React Native array.length appears to be returning a value

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&apos;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.

Answer №1

Array is always passed by reference. When you log all three items,

  1. messages was initially an empty array // passed by reference
  2. therefore messages.length was 0 // passed by value
  3. therefore messages[0] was undefined. // passed by value

However, since console.log(messages) logs by reference, it later updates to the correct data, but the other two logs do not update.

It appears that the messages array being passed is asynchronously retrieved, consider using async await and only execute the function once the messages data has been received.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it acceptable to have an empty dependency array in React.useEffect?

Within my child React component, I receive an itemList prop from the parent component. This prop is an array of objects that contain data fetched from an endpoint. My goal in the child component is to enhance each object in the itemList array by adding mo ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

Creating a Redis client in Typescript using the `redis.createClient()` function

I'm currently trying to integrate Redis (v4.0.1) into my Express server using TypeScript, but I've encountered a small issue. As I am still in the process of learning TypeScript, I keep getting red underline errors on the host parameter within th ...

Exploring Angular data iteration with Tab and its contentLearn how to loop through Tab elements

Upon receiving a response from the API, this is what I get: const myObj = [ { 'tabName': 'Tab1', 'otherDetails': [ { 'formType': 'Continuous' }, { 'formType& ...

Unable to position text in the upper left corner for input field with specified height

In a project I'm working on, I encountered an issue with the InputBase component of Material UI when used for textboxes on iPads. The keyboard opens with dictation enabled, which the client requested to be removed. In attempting to replace the textbox ...

Does the router navigate function instantly update the router URL?

I'm testing whether the navigate function will immediately alter the router URL upon execution. this.router.navigate(['/home/products']); if (this.router.url.includes('/home/products')) console.log('URL has been changed&apos ...

Stop the inheritance of static components in a feature module by protecting the router-outlet

I am in the process of dividing my app into multiple feature modules. Currently, I am using only the router-outlet inside a component within a feature module. However, this approach brings along all the static components such as the navbar and footer. How ...

Rendering a component in React based on multiple conditions

Checking sessionStorage and another state variable before rendering a component is essential for my application. I want to avoid showing the same message multiple times within the same session. This is how I have implemented it: const addSession = (noteId: ...

Generating a JSON file dynamically containing hierarchical data

I am looking to create a JSON file structure similar to the example provided in this post, but I need it to be dynamic. The current solution is specific for "entry1" and "entry2", however, I want the flexibility to use any entity name such as customer, add ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

Steps to insert a personalized attribute into a TypeScript interface

UPDATED EXPLANATION: I'm fairly new to TypeScript, so please bear with me if this question seems basic. I'm working with an existing library (ngx-logger) that I don't want to or can't modify. My goal is to create a service that generat ...

Tips on utilizing the i18n t function within a TypeScript-powered Vue3 component

I am working on creating a control that can automatically manage interpolation for internationalization (i18n) strings: <script lang="ts"> import { ref, defineComponent, inject } from "vue"; import type { InterpolationItem, Inter ...

I'm curious about the type I can set for the first parameter of setState in TypeScript. Is there a way to pass a dynamically generated state object to setState?

When trying to pass a newState object to setState and add some additional properties under certain conditions, I encountered a type error: I attempted to define the new State as Pick<ItemListState, keyof ItemListState> but received a type error ...

Implementing canActivate guard across all routes: A step-by-step guide

I currently have an Angular2 active guard in place to handle redirection to the login page if the user is not logged in: import { Injectable } from "@angular/core"; import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from ...

Sending a parameter to a confidential npm module

I've developed a custom npm module that can be used in my applications by including this code snippet in the HTML: <app-header-name></app-header-name> Here is the TypeScript code inside the npm package: import { Component, OnInit } from & ...

What is the best way to trigger a method after an old component has been removed from the DOM while navigating within Angular

I am facing a challenge where I need to execute a method on ComponentB after a routerLink is clicked, causing the navigation from ComponentA to ComponentB. It is crucial that this method is triggered only after the entire navigation process is complete (i. ...

Displayed even when data is present, the PrimeNg empty message persists

I have set up a PrimeNg table to display data with an empty message template like this: <ng-template pTemplate="emptymessage"> <tr> <td> No records found </td> </tr> </ng-template> ...

I'm diving into the world of Typescript and trying to figure out how to use tooltips for my d3 stacked bar chart. Any guidance on implementing mouseover effects in Typescript would be greatly

I am currently facing some issues with the code below and need guidance on how to proceed. I am new to this and unsure of how to call createtooltip. Any assistance would be greatly appreciated. The error message states that createtooltip is declared but n ...

Could it be that the TypeScript definitions for MongoDB are not functioning properly?

Hello everyone, I'm facing an issue with getting MongoDB to work in my Angular 4 project. In my code, I have the db object as a client of the MongoClient class: MongoClient.connect('mongodb://localhost:27017/test', (err, client) => { ...

The AOT Compilation error occurs in Angular2 RC6 when trying to call the function RouterModule.forChild(ROUTES) which is not supported

Operating Environment: Windows 10, IntelliJ 2016.2, node Angular Version: 2.0.0-rc.6 Language: [all | TypeScript X.X | ES6/7 | ES5] Typescript ES6 Node (for Ahead of Time Compilation issues): node --version = Node 4.4.7, NPM 3.10.6 The AOT com ...