Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Axios forcing "any" type on response type

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
        })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading