Reputation: 296
I am trying to fetch data with Axios in my typescript react project, and I set the response type in axios to be of my CartItemType, however axios forces the response type to be of CartItemType and any, which breaks my code. Why does it force the "any" type? How to get rid of it?
export type CartItemType = {
id: number;
category: string;
description: string;
image: string;
price: number;
title: string;
amount: number;
};
const App = () => {
const [data, setData] = useState<CartItemType[]>([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
axios.get<CartItemType[]>("https://fakestoreapi.com/products")
.then(products => {
setData(products);
setLoading(false);
})
}, [])
the error appears at the products argument in the then function. When I hover over the error it reads:
Argument of type 'AxiosResponse<**CartItemType[], any**>' is not assignable to parameter of type 'SetStateAction<CartItemType[]>'.
Type 'AxiosResponse<CartItemType[], any>' is not assignable to type '(prevState: CartItemType[]) => CartItemType[]'.
Type 'AxiosResponse<CartItemType[], any>' provides no match for the signature '(prevState: CartItemType[]): CartItemType[]'.ts(2345)
why is there this ",any" type?
Upvotes: 0
Views: 3295
Reputation: 137
axios is returning response rather than the type itself, so it should be
axios.get<CartItemType[]>("https://fakestoreapi.com/products")
.then(response=> {
setData(response.data); // <-- response.data should be CartItemType[]
setLoading(false);
})
Upvotes: 2