I anticipated receiving an array of objects from the API response, but instead, I am dealing with an array of Promises in my React app using TypeScript

Apologies if this question seems basic to you. I am still new to TypeScript and working with Promises. Despite searching on various platforms, I couldn't find a relevant solution. Can you assist me in receiving an array of objects instead of promises? Additionally, I would appreciate it if you could suggest some resources for learning React with TypeScript. Thank you in advance!

index.ts

    interface IFetchLikes {
      item_id: string;
      likes: number;
    }

const fetchLikes = async (): Promise<IFetchLikes[]> => {
    const response = await axios.get<IFetchLikes[]>('https://us-central1-involvement-api.cloudfunctions.net/capstoneApi/apps/PmGqiCAY4CG3PZPHNcEG/likes');
    return response.data;
  };

  console.log('Response: ', fetchLikes());

Answer №1

Returning IFetchLikes[] directly from the fetchLikes function without a promise is not possible.

The reason for this limitation is that promises are essential to synchronize async code execution. Since axios API calls are asynchronous, the code needs to wait for the data to be returned.

There are two approaches to handling this scenario:

  1. Reorganize the subsequent function or executable code after using await keyword. Check out this TypeScript example
  2. Utilize the use of then to execute the code after the promise has resolved. Take a look at this TypeScript example

Refer to the following documentation for more details: https://www.typescriptlang.org/docs/handbook/react.html

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 unified environment variable for Angular 2 and ASP.NET Core MVC: A comprehensive guide

In my ASP.NET Core MVC project, I am utilizing an Angular 2 application. Both the Angular 2 app and the Startup.cs file contain code that is specific to different environments. For example, using http://localhost as the web service URL during development ...

The replacer argument of the JSON.stringify method doesn't seem to work properly when dealing with nested objects

My dilemma is sending a simplified version of an object to the server. { "fullName": "Don Corleone", "actor": { "actorId": 2, "name": "Marlon", "surname": "Brando", "description": "Marlon Brando is widely considered the greatest movie actor of a ...

How do I verify if a boolean variable has been changed within an Angular service?

In my MatHorizontalStepper parent component, I utilize the subscribe function to monitor changes in an Observable within a service. The purpose is to automatically progress to the next step in the stepper when the observable switches from false to true. D ...

I am curious if there exists a VSCode plugin or IDE that has the ability to show the dependencies of TypeScript functions or provide a visual representation

Are there any VSCode plugins or IDEs available that can display the dependency of TypeScript functions or show a call stack view? I am looking for a way to visualize the call stack view of TypeScript functions. Is there a tool that can help with this? Fo ...

A guide to implementing previousState in React hooks with TypeScript

I am trying to grasp the concept of using previous state with react hooks in typescript. The code snippet provided below does function, however, it throws an error stating: Type 'number' is not assignable to type 'HTMLDivElement'. Whi ...

Issue with TypeScript Decorator Not Properly Overriding Get/Set Functions for Instance Properties

I'm struggling with creating a TypeScript decorator that modifies the get method for a property within a class. The issue I'm facing is getting it to affect instances of the class. Below is an example scenario: function CustomDecorator() { r ...

Can an excessive amount of classes cause my Angular application to run sluggishly?

Within my Angular 7 application, I have generated approximately 200 to 300 classes for model types (e.g. component.model.ts) solely for type checking purposes. I have not instantiated any objects from these classes. As I navigate through the application, ...

Steps for linking HTTP requests in Angular 2 depending on the type of response

My attempt to create an api call from a remote server and then, if an error occurs, make another request from my local server is not working as expected. I am encountering errors and need help to determine if my approach is feasible. Here is the code snip ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Change a nullable string property within an interface to a non-nullable string property

Looking at two interfaces, one with a nullable vin and the other without: interface IVehicle { vin: string | null; model: string; } interface IVehicleNonNullVin { vin: string; model: string; } The goal is to convert a model from IVehicle ...

Eliminate a specific choice from a drop-down menu in an Angular application

I am implementing a feature where clicking on a button adds more select drop downs. I want to ensure that the selected options in these new dropdowns do not duplicate any already chosen options. Below is the code snippet used for the select drop down: < ...

When Utilizing an async Task Method, DbContext is Properly Disposed

Currently, I have set up an async Task method to handle the IAuthenticationFilter interface. After logging in successfully, I can access an API with no issues when it has this attribute. However, if I revisit the API later on, an exception is thrown. publ ...

Implementing NestJS: Integrating TypeORM Datasource without relying on class dependency injection

I have a unique situation that requires some help. Our team is in the process of integrating nestjs into our current express codebase. Previously, we were using Typeorm 0.2 and recently upgraded to 0.3. Due to the fact that we utilize functions instead of ...

Retrieve the array from within the string

Any suggestions on how I can extract the array from this string? The current string is: "['Biller.Customer.Data@Taxonomy', 'Product.Platform and Enterprise Services Data.Data@Taxonomy']" I need to extract it to look like thi ...

At what point does the constructor of an injected service in Angular execute?

When using @Injectable({providedIn: 'root'}) in Angular 7 for a service, the constructor of the service executes when exactly? Is it upon the creation of a component that utilizes it as a dependency or does it wait until a method within the servi ...

Is there a hashing algorithm that produces identical results in both Dart and TypeScript?

I am looking to create a unique identifier for my chat application. (Chat between my Flutter app and Angular web) Below is the code snippet written in Dart... String peerId = widget.peerid; //string ID value String currentUserId = widget.currentId ...

How can the adapter pattern be implemented in Angular when dealing with an HTTP response containing an array of objects?

Using the adapter pattern in Angular, I have successfully adapted Http response to an 'Invoice' object. However, I am facing a challenge when one of the properties inside the 'Item' is an array. In this scenario, the 'items' ...

Can we define the input and return types for functions using httpsCallables?

I have implemented a callable function in my app to update user claims. The functions are written in Typescript and I have used an interface to define the required data shape for the function. My objective is to make it easier for any developer on the tea ...

What are the best strategies for utilizing AnimatePresence for smooth and seamless transitions?

In my upcoming app, I am working on creating a seamless entry/exit animation using Framer Motion's AnimatePresence component. While experimenting with the delay feature, I encountered an issue where only one component would animate properly, while the ...

Clicking on the image in Angular does not result in the comments being displayed as expected

I find it incredibly frustrating that the code snippet below is not working as intended. This particular piece of code was directly copied and pasted from an online Angular course I am currently taking. The objective of this code is to display a card view ...