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?
- res.data returns an Object
- I also tried to destructure the data as shown here https://docs.strapi.io/dev-docs/integrations/react#example-1:
return axiosInstance.get<T[]>(this.endpoint).then(({ data }) => data.data)
but it gives an error: Property ‘data’ does not exist on type ‘T[]’.
Any idea how can I solve this? Thank you
2
Answers
By creating an additional interface to match the response I was able to solve the problem and maintain type annotation:
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:
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.