The Axios GET method retrieves a response in the form of a string that represents an object

I have developed a function that triggers an axios Request. I am working with typescript and I am avoiding the use of any for defining return data types of both the function and the axios request itself.

The issue arises when the returned object contains the parameter id, which in turn is an object. To be honest, I have never encountered such a structure before. I am unsure about its nature and whether it involves some fundamental concepts that I might not be familiar with. It has been challenging to find relevant information through online searches.

I aim to create a custom typescript interface based on this object. However, I am struggling to figure out where to begin.

Any assistance will be highly appreciated.

This snippet represents a portion of the resulting object:

 {
          data{
           '12345': { // params.id --> causing my poblem
                   address: {
             ...,
        }}}
    }
 

Here is my function:

async function fetchData (): Promise<IReturnData[]> {
const {data} = await axios.get<IReturnData>(`....${id}`) // in our case 12345
return Object.entries(data.data)[0];

}

How should I define the interface IReturnData ?

    export interface IReturnData {
      data {
          string: { adress: Adress......
    }}}
   

    or 
    export interface IReturnData {
      data  {
          "1234 but that will change on every request": {
             adress: Adress......
     }}}
        

Answer №1

Utilizing Mapped Types could be the most effective approach.

Although not flawless, examining the example below or visiting this playground for more insights...

interface MyModel {
    [key: string]: Address;
}

const goodExample: MyModel = {
    "12345": {
        country: "Germany"
    }
}

const badExample: MyModel = { // Unfortunately, this also functions, but limiting it to one key seems challenging
    "12345": {
        country: "Germany"
    },
    "23456": {
        country: "Germany"
    }
}

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

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...

What is the best way to disable list items in a UI?

Check out my assortment: <ul class="documents"> <li class="list_title"><div class="Srequired">NEW</div></li> <li class="doc_price>1</li> <li class="doc_price>2</li> <li c ...

Http service not found

I am facing a problem with injecting HTTP into my Angular 2 application. Everything was working smoothly a few days ago, but now I am encountering this error: ORIGINAL EXCEPTION: No provider for Http! Here is the code snippet from main.ts: import { pl ...

Challenges with implementing TailwindCSS classes in a Next.js application

I've encountered some issues in my nextJS app with utilizing certain TailwindCSS classes such as top, left, or drop-shadow. Even after attempting to update Tailwind from version 1.9.5 to 3.3.3, I have not seen any changes. I believe that I am import ...

Invoke cloud functions independently of waiting for a response

Attempting a clever workaround with cloud functions, but struggling to pinpoint the problem. Currently utilizing now.sh for hosting serverless functions and aiming to invoke one function from another. Let's assume there are two functions defined, fet ...

How can you fix the "bad value" response in mongodb when utilizing query parameters in the url?

{ "ok": 0, "code": 2, "codeName": "BadValue", "name": "MongoError" } Whenever I attempt to use query parameters skip and limit in the url, this error message pops up. localhost:5 ...

Leveraging numerous identifiers in jQuery

I created a small jQuery script to check if the input box value is greater than 5, but I have two tags with IDs and only one of them seems to be working. <div id="register"> <form id="register"> <input id="first" type="text" /> <a ...

Unable to retrieve JSON data from converting TXT using JavaScript, resulting in undefined output

After converting txt to JSON, I encountered an issue. const txt = JSON.stringify(`{ ErrorList: [{ 80: 'Prepared' }], Reference: [ { 'Rule Name': 'Missing 3', 'Rule ID': 1, 'Rule Des& ...

Changing properties of a parent component from a child component in Angular 2

Currently, I am utilizing the @input feature to obtain a property from the parent component. This property is used to activate a CSS class within one of the child components. Although I am successful in receiving the property and activating the class init ...

Using CSS in combination with AngularJS, you can create a dynamic growth effect for a div element that initially

I am currently using AngularJS to dynamically add divs to a section. My goal is to have each div start with a static width and then grow dynamically as I continue to add more divs. How can I achieve this? The following code is not producing the desired re ...

I am looking to fetch information from a different Firestore collection by looping through data using a forEach method within an onSnapshot function

I'm struggling to grasp the concept of rendering data from Firestore in my project. I've searched extensively but haven't been able to find a solution that fits my requirements. Background Information In my Firestore database, I have collec ...

Issues with JSONPATH in typescript failing to grab any values

Searching for a specific config item validity using JSON path can be achieved by specifying the key name condition. This process works seamlessly on platforms like , accurately extracting the desired value: https://i.sstatic.net/2ffAAnNM.png In Typescrip ...

Java servlet is unable to interpret the name of an html select tag

Currently, I am implementing a feature where table rows with select boxes are added dynamically and the values of these select boxes are retrieved in a servlet. The process of adding the select boxes is functioning properly; however, when attempting to ret ...

Using jQuery to assign the value of a hidden element to data being posted

When using jQuery's post() method to call an ajax action that returns JSON data ({"Success": "true" } or {"Success": "false"}), the value of a hidden HTML element is supposed to be set to the Success value in the returned object. However, after settin ...

Avoiding an event from spreading in Angular

I am working on a navigation setup that looks like this: <a (click)="onCustomParameters()"> <app-custom-start-card></app-custom-start-card> </a> When the user clicks on the app-custom-start-card, the onCustomParame ...

Proper usage of a method within another method in a Vue component

Currently, I am extracting GPS data from an image using exifjs. My objective is to convert the latitude and longitude variables into a decimal variable as illustrated below: <template lang="html"> <div class="upload-wrap"> <button cla ...

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 ...

What is the reason for the service not providing an encoded string as output?

A service has been created to encode passwords using the ts-md5 library in Angular: import { Injectable } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Md5 } from 'ts-md5/dist/md5'; @Injectab ...

Safely transmitting client-side encrypted information between individuals

I am developing a service that will keep personal information about a specific user, which should only be accessible by the author and the intended recipient. I want to encrypt the data on the client-side and store the encrypted version on the server. Res ...

Error occurs in console when using .getJSON with undefined JSON, but does not happen when using embedded data

Can someone help me understand why I'm getting an 'undefined' response when I use console.log(tooltipValues), but there's no issue with console.log(tooltipJSON). I've noticed that when I embed the data directly in my JS code, ever ...