Elements can only be added to the array at the 0th index

In the process of developing a function, I encountered an issue where all elements added to the array were only stored in Array[0] of the rowData. The data is retrieved from a database.

private createRowData() {
        var rowData:any[] = [];
        this.wakanda.catalog.then(ds => {
            ds.Group.query({select : 'groupName'}).then(op => {
                for(let entity of op['entities']){
                    rowData.push(
                    {row : entity.groupName});
                }
            });
        });
        return rowData;
    }

The current output looks like this:

https://i.sstatic.net/jpIVs.png

I am aiming for an output similar to this:

https://i.sstatic.net/Oshnw.png

If anyone has suggestions on how to resolve this issue, it would be greatly appreciated.

Thank you in advance!

Answer №1

The function above includes a DB call that is asynchronous, and the response is sent before waiting for the result.

As a consequence, the rowData.length will be 0 in this scenario.

To address this issue, it's recommended to send the result after receiving the callback response.

You can modify the code as follows:

    private createRowData() {
        return new Promise((resolve, reject) => {
            var rowData: any[] = [];
            this.wakanda.catalog.then(ds => {
                ds.Group.query({ select: 'groupName' }).then(op => {
                    for (let entity of op['entities']) {
                        rowData.push({ row: entity.groupName });
                    }
                    resolve(rowData); // Send the result from here
                });
            }).catch(reject);
        })
    }

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

What is the most effective method to prevent postback controls from activating before the page is fully loaded?

My website contains high-quality graphics, which may lead to slow download times for users with poor internet connections. As the browser is still loading, users often access form options and submit their information prematurely. This premature submission ...

Avoid the ability for individuals to interact with the icon embedded within a button

I'm currently working on a website where users need to interact with a button to delete an "Infraction." The button has a basic bootstrap style and includes an icon for the delete action. <button referencedInfraction="<%= i.infractionID %>" ...

Converting strict primitive types to primitive types in Typescript

I have a function that parses a string into a value and returns a default value if it fails. The issue is that this code returns too strict types for primitives, such as `false` instead of `boolean`. How can I resolve this? Should I utilize some form of ...

jQuery puzzle: a form within a form within a form

I am facing a bit of a dilemma with a partially working solution. The scenario is this - I am using a basic .load() function attached to a <select> element to fetch another form populated through PHP/MySQL. What I intend to achieve is for this newly ...

Issue encountered when running a minification build on Angular 5

After successfully updating my Single Page Application (SPA) from Angular 4 to Angular 5 along with all dependencies, everything seemed to be working well. Both the development and production builds were functioning without any errors or warnings. However ...

Is Angular capable of displaying a date within a specific timeframe using ng-show?

So I have a button that, when clicked, displays a list of data. I am adding a unique font awesome icon in there if the JSON key value exists. However, here lies the issue. The particular key happens to be a date. I need my ng-show function to check whether ...

AngularJS - Issue with retrieving the most recent entry during $routeChangeStart event

I am utilizing the $routeChangeStart function to redirect authorized users to specific URLs and prevent unauthorized access to special pages. In addition, I have dynamically generated pages that can be accessed via their unique page slugs. To achieve this ...

Mixing controllers with the same name in AngularJS from different modules can lead to

Recently, while working on an AngularJS web application with multiple sub-modules, I encountered a situation where two sub-modules had controllers with the same name due to them both having CRUD functionality. Here's a snippet of the code structure: ...

The component's state consistently reverts to its initial state

I am working with a component called DataGrid that has the following state: const [rows, setRows] = useState([ { id: 1, lastName: 'Snow', firstName: 'Jon', status: 'Sold'}, { id: 2, lastName: 'Lanniste ...

Is dynamic data supported by Next.js SSG?

I'm currently developing a web application with Next.js and I need clarification on how Static generated sites work. My project is a blog that necessitates a unique path for each blog entry in the database. If I were to statically generate my web appl ...

Error encountered when deploying the app to the live server: 500 Internal Server Issue

I am encountering an issue with my ASP.Net web app's ajax file upload feature. While it works perfectly on my local host machine during testing, I face a 500 Internal Server error when I try to publish it to a website. The console output in Google Chr ...

What is the best way to display API error messages to the user?

When a user tries to upload a file that is not an image, I need to display the error message returned from a REST API. The JSON response received from the API will look something like this: { "publicError": "Could not be uploaded, it is not an image! ...

Struggling to implement my reusable React component within a React Bootstrap modal

I have developed a reusable textarea React component: import React from 'react'; import '../form-input/form-input.styles.scss'; const TextAreaComponent = ({ handleChange, label, ...otherProps }) => ( <div className="group"> ...

Confusing directions about parentheses for "this.fn.bind(this)(super.fn(...args)"

While reviewing a project, I came across code that can be simplified to: export abstract class Logger { private static log(level: LogLevels, ...args: Array<any>) {/**/} public error(...args: Array<any>): LogData { return Logger ...

Strange behavior in Vue observed. The v-if directive is not properly monitoring changes

I am facing a perplexing issue. I have a basic service and a Vue component. In the template, there is a v-if directive that monitors a variable in the service (if it is true, a div should be displayed, otherwise not). Everything works fine when I initial ...

Transforming the timezone of a date from the Backend to the timezone selected by the user in the User

I have an API that provides dates in the format: 12/23/2023 at 03:31 a.m. CST My goal is to convert this to a date with the user-selected timezone in the following format: 12/23/2023 at 7:31 p.m. The timezone part is not required for display in the UI. c ...

Initiate the countdown when the button is pushed

Recently ran into an issue where a button triggers a command to a Perl script, causing the page to continuously load for 60 seconds. To provide users with transparency on when the Perl script will be finished running, I implemented a JavaScript countdown t ...

The program abruptly shut down with error code 127. Any idea why this occurred?

I'm having issues while attempting to create an app from a script. When I run "ionic serve," the following errors occur: [error] Error: Job name "..getProjectMetadata" does not exist. at Observable._subscribe (C:\Users\Bhanu\Desktop&bs ...

What causes my local storage to be cleared whenever I refresh the page in React with Redux?

What causes my local storage to reset to empty whenever I refresh the page? I am attempting to save data to local storage that is also passed to my redux state, but I am unable to do so. const retrieveLocalStorage = () => { const oldExpenses = JSON ...

Sort div elements based on checkbox filters

I have a set of checkboxes that I want to use for filtering purposes. <div class="filter"> <div class="checkbox"> <label><input type="checkbox" rel="canada"/>Canada</label> </div> <div class="chec ...