I have this category interface
export interface ISubCategory {
_id: string,
name: string,
createdAt: Date,
updatedAt: Date
}
export interface ICategory {
_id: string,
createdAt: Date,
updatedAt: Date,
name: string,
subCategories: ISubCategory[],
_v? : string | number
}
export interface ICategories{
categories : ICategory[]
}
On my home page, I called the API to get categories
const fetchCategories = async () => {
const data : ICategories = await getCategories()
setCategories(data)
}
useEffect(() => {
fetchCategories()
}, [])
and the getCategories is here
export async function getCategories (){
try {
const response = await axios.get('/categories')
const data = response.data.data
return data
} catch (error) {
console.log(error)
return error
}
}
And when I passed these categories to child component an error occur. Type 'ICategories | []' is not assignable to type 'ICategory[]'. Type 'ICategories' is missing the following properties from type 'ICategory[]': length, pop, push, concat, and 29 more. here is how I am passing categories to child component and receiving it in child component
return (
<Div>
<DropDownContextProvider>
<Header categories={categories} />
<Slider />
</DropDownContextProvider>
</Div>
)
and here how I am receiving it
const Header = ({ categories }: ICategories ) => {
}
CodePudding user response:
in the return response, you need to build the object to support the ICategories
interface
export async function getCategories (){
try {
const response = await axios.get('/categories')
const data = response.data.data
return {categories: data}
} catch (error) {
console.log(error)
return {categories: []}
}
}
CodePudding user response:
The categories are of type array and changed my interface to this
export interface ISubCategory {
_id: string,
name: string,
createdAt: Date,
updatedAt: Date
}
export interface ICategory {
_id: string,
createdAt: Date,
updatedAt: Date,
name: string,
subCategories: ISubCategory[] | [],
_v? : string | number
}
and removed ICategories interface and the categories state set as ICategory[] | []
const [categories, setCategories] = useState<ICategory[] | []>([])
const fetchCategories = async () => {
const data = await getCategories()
setCategories(data)
}
useEffect(() => {
fetchCategories()
}, [])
and then received props in header component as this
const Header = ({ categories }: { categories:ICategory[] | [] }) => {
}