Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return data from an axios get request

Trying to use the below response interface for data sent back by my server. Only problem is response.data.data is apparently blank. However, response.data contains the actual data.

When I hover over the last data in response.data.data it shows it's type as: (Property) ProductResponse.data: ProductDTO.

If I modify my axios.get<>() to return a Product with response.data passed to the constructor everything works fine. But I keep running across this interface pattern being used, so I'm trying to use it myself.

Probably a quick one for the experts, thanks!

import axios from "axios";
import Product, { ProductDTO } from "@/models/Product";

interface ProductResponse {
  status: number;
  message: string;
  data: ProductDTO;
}

// Rework to a more generic API
export abstract class ProductApi {
  private static productAxios = axios.create();

  static async getProduct(id: number): Promise<Product> {
    let response = await this.productAxios.get<ProductResponse>(
      "http://localhost:8080/api/product/" + id
    );
    console.log(response.data.data);
    return new Product(response.data.data);
  }
}
like image 962
Ryan W Avatar asked Jun 23 '26 03:06

Ryan W


1 Answers

if you check the types of the Axios get() function, you'll see that it has this implementation:

  get<T = any, R = AxiosResponse<T>>(url: string, config?: AxiosRequestConfig): Promise<R>;

https://github.com/axios/axios/blob/master/index.d.ts#L137

So the first type passed (T) is the type of the data, not the type of the response. In your case, you'll have to implement it this way:

this.productAxios.get<Product, ProductResponse>

Your data is indeed in response.data :)

like image 54
nicolasrigaudiere Avatar answered Jun 25 '26 18:06

nicolasrigaudiere