I created a single type called hero-section
When I call http://localhost:1337/api/hero-section?populate=*
I get the response what I expect.
{
"data": {
"id": 1,
"attributes": {
"Hero_text": {
"id": 1,
"Title": "Test title",
"Content": "Test content"
},
"Hero_button": {
"id": 1,
"Title": "button title",
"Link": null
},
}
},
"meta": {}
}
My nuxt component is this
<script setup lang="ts">
import Hero from '../types/Hero'
const { find } = useStrapi()
const config = useRuntimeConfig()
const hero = await find<Hero>('hero-section', { populate: '*' })
const urlBg = `url("${config.public.strapi.url}/uploads/bg.png")`
</script>
<template>
<section>
{{ hero.data.attributes.Hero_text.Title }}
{{ hero.data.attributes.Hero_text.Content }}
</section>
</template>
I get the correct data here, but the attributes
part of the variable is marked red by vscode with this error: Property 'attributes' does not exist on type 'Strapi4ResponseData<Hero>[]'.ts(2339)
How do I fix this?
Radharadhya_Dasa:
Strapi4ResponseData
How does your Hero type look like ? Because technically it’s not a hero type it’s a DATA (Or whatever you want to call the generic response) type so something like this ?
interface Data<T> {
data: {
id: number;
attributes: T;
};
meta: Record<string, unknown>;
}
interface Hero {
Hero_text: {
id: number;
Title: string;
Content: string;
};
Hero_button: {
id: number;
Title: string;
Link: string | null;
};
}
const myData: Data<Hero> = {
data: {
id: 1,
attributes: {
Hero_text: {
id: 1,
Title: "Test title",
Content: "Test content",
},
Hero_button: {
id: 1,
Title: "button title",
Link: null,
},
},
},
meta: {},
};
Hope this helps
The Hero type definition is his
type Hero = {
data: {
id: number
attributes: {
Hero_text: { id: number; Title: string; Content: string }
Hero_button: { id: number; Title: string; Link: string }
Hero_image?: { data: { url: string } }
}
}
}
export default Hero
I am still new to typescript, so generics still confuses me.
Your type also gave me the same error.
So to try explain it the “data” interface I created has a Hero one containing what is part of the Hero.
The response you get back contains, data with attributes. Which is NOT Hero
The const myData
is not needed btw also you need to export the interface
export interface Hero
1 Like
For future reference,
You using the ‘find’ function, which returns an ARRAY type Strapi4ResponseData .
As you stated you need to get a single type, you can use findOne, which returns type of Strapi4ResponseData, where data.attributes is defined