skip to Main Content

I am calling Strapi API endpoint: get(‘/articles’) to get an array of articles.

const axiosInstance = axios.create({
  baseURL: API,
});

class APIClient<T> {
  ...
  getAll = () => {
    return axiosInstance.get<T[]>(this.endpoint).then((res) => res.data);
  };
  ...

T is a generic type, in this case Article interface is passed: new APIClient<Article>("/articles")

Response scheme is:

Object {
   data: Object {
      data: [] <- Array of Articles

How do I format the data to get the array of Articles inside that Object?

Any idea how can I solve this? Thank you

2

Answers


  1. Chosen as BEST ANSWER

    By creating an additional interface to match the response I was able to solve the problem and maintain type annotation:

    interface ApiResponse<T> {
       data: T
    }
    

    and then adding it to axios.get I was able to access the 2nd data property to return an array of Articles instead of an Object:

    return axiosInstance
          .get<ApiResponse<T[]>>(this.endpoint)
          .then((res) => res.data.data);
    

  2. The error you are showing is the Typescript error, not the actual error that server returns.

    The fastest way would be just replace <T[]> with <any> and figure out the proper type later.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search