Retrieve intricate information from an API, generate an array of objects, and loop through them

I am attempting to create an array of intricate objects from the following data:

My goal is to utilize this object array to generate components using map()

  • To structure the response type, I utilized :

// ... other types like Tag
export type DatasetInfoResult = {
  license_title: string
  relationships_as_object: string[]
  maintainer_email: string
  tags: Tag[]
    //... all the params
}

export type DatasetInfoResponse = {
  help: string
  success: boolean
  result: DatasetInfoResult
}

Here is a snippet of my code:

  • datasetIDs is an array of strings containing dataset names such as sample-dataset-1
  • getDataset fetches the API address and works correctly

export async function getAllDatasets() {
 
    const datasetsIDs = (await listDatasets())
    let allDatasets: DatasetInfoResult[]

    datasetsIDs.map( async id => {
        allDatasets.push( await getDataset(id) )

    })

 return allDatasets

Error message: TypeError: Cannot read properties of undefined (reading 'push')

Exploring an alternative approach:


export async function getAllDatasets() {
 
    const datasetsIDs = (await listDatasets())
    let allDatasets: DatasetInfoResult[]

    
    for (let i = 0; i <= datasetsIDs.length; i++ ) {
    
    const resp = ( await getDataset( datasetsIDs[i]) )
    allDatasets = [...allDatasets, resp]
    // allDatasets.push(resp)
    
  }
 return allDatasets

Error message: allDatasets is not iterable

What is the best way to achieve my objective of retrieving and utilizing multiple data sets?

Answer №1

Attempting to push to undefined is the issue in the initial example due to allDatasets not being initialized with a value.

let allDatasets: DatasetInfoResult[] // since this is undefined, pushing to it is not possible

datasetsIDs.map( async id => {
  allDatasets.push( await getDataset(id) )
})

A potential solution would be

let allDatasets: DatasetInfoResult[] = []

datasetsIDs.map( async id => {
  allDatasets.push( await getDataset(id) )
})

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

Creating a personalized theme for Material UI 5.0 using Typescript with React

Having some trouble customizing a theme in Material UI 5.0 with typescript. theme.ts import { createTheme } from '@mui/material'; declare module '@mui/material/styles' { interface Theme { custom: { buttonWi ...

Utilizing a string variable as a property name for dynamic typing

I am looking to dynamically create a type with a property name based on specified parameters. Although I can successfully create the object, I am facing challenges when trying to create the actual type. This dynamic type creation is essential for compositi ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Repeating promises resolutions yields stagnant outcomes

Within my Angular project, I am working with two distinct components. parent.component.ts mypromise = this.httpClient.get<any>('http://localhost').toPromise() parent.component.html <app-children #child [promise]="mypromise"></a ...

I'm curious if there is an uncomplicated method to host a JSON file that is both readable and updatable within the Google Cloud Platform

My goal is to host a JSON document that will act as a hosted version of json-server. While I could use My JSON Server for this purpose, I am opting to transition my architecture to GCP and want to become more familiar with it. Initially, I explored the St ...

What is the best way to remove quotes from a normal array that has been inserted into an HTML dataset?

I'm currently utilizing Express.js on my server with EJS as the template engine. Once I retrieve an array from my database and send it to EJS, I store the data in a dataset. However, when attempting to access this dataset using vanilla JavaScript, I ...

Java code experiencing issue with Google's URL shortening API

I am working on a code that utilizes the Google URL shortening service. While the code is running smoothly, it seems to return a URL that redirects me to the Google login page. Is there a way for my code to authenticate with Google and then access the shor ...

How to transfer a parameter in Angular 2

I am currently facing a challenge in passing a value from the HTML file to my component and then incorporating it into my JSON feed URL. While I have successfully transferred the value to the component and displayed it in the HTML file, I am struggling to ...

Issues with saving nodes containing sizable properties in Neo4j

When working with Neo4j in Java using CYPHER and JSON through http://hostname:7474/db/data/transaction/commit, I encounter an issue. In my testing, I am trying to create nodes using the following CYPHER statements: MERGE (a:LABEL1 { name: 'nameNNN&a ...

The NestJS Backend is always being asked by Grafana to access the /api/live/ws endpoint

After successfully setting up Grafana and Grafana Loki with my NestJS Backend, everything seemed to be working fine. However, I started getting a 404 error from my NestJS because Grafana was requesting the /api/live/ws route. Is there a way to disable thi ...

Is there a method to define an 'internal' property within a TypeScript type?

I created a custom 'library' in Angular and TypeScript. This library is distributed as a *.ts package within other Angular workspaces. Within this library, I have an exported class that contains various properties. One specific property in thi ...

Issue: Catching errors in proxy function calls

I am currently using Vue 3 along with the latest Quasar Framework. To simplify my API calls, I created an Api class as a wrapper for Axios with various methods such as get, post, etc. Now, I need to intercept these method calls. In order to achieve this ...

Navigating to the detail page following a POST request in RTK query: A step-by-step guide

In my React RTK-query form, I am facing an issue where after a POST request is made, the form should navigate to the next step. However, in order to do that, I need to obtain the id of the newly created record. The backend auto-increments the id and does n ...

Create a function that takes an array as input and retrieves the element in the array that corresponds to the specified question

To solve this problem, I'm tasked with creating a function called findAnswers(answers, questions). The function should return the item in the array that corresponds to the given question. If none of the student's answers match the question, the f ...

"Discovering the secrets of incorporating a spinner into Angular2 and mastering the art of concealing spinners in Angular

When experiencing delay in image loading time, I need to display a spinner until the image loads completely. What is the best way to achieve this on the Angular 2 platform? <div id='panId' class="container-fluid" > This section ...

Exploring the depths of JSON: Unraveling the secrets of reading dynamic object data

Currently, I am receiving a JSON file from another app and my goal is to parse it in order to extract the data contained within. The JSON includes user-defined dynamic data with changing key/value pairs, which has left me feeling uncertain about how to eff ...

The API request is failing after waiting for 4 minutes

My API call from the client side is failing after 4 minutes of waiting. Interestingly, when I run the same query in Oracle SQL Developer, it takes the same time but displays the data successfully. For my frontend, I am using ReactJS and for the backend, ...

Comparing JSON Objects in Javascript

I'm in the process of developing a web application that retrieves data from a server and displays it to the user. The script pulls data from the server every 10 seconds, and if there's any change in the data, it alerts the user. Currently, the co ...

Utilizing D3 visualization with an API-driven JSON web service

I am currently trying to create a bar chart based on the code from this example provided in this tutorial. Instead of using TSV files, I have modified the code to work with JSON data. I have verified that the endpoint http://localhost:3000/graphs/data from ...

Typescript declaration for a Record containing a specified set of fields

I am working on the code below: type MyDict = { [k: string]: unknown; }; function fn<T extends MyDict>(items: T) { const functionDict: { [k: string]: (val: keyof T) => void } = Object.fromEntries( Object.keys(items).map((key: keyof T) =&g ...