使用axios响应类型来响应打字稿

时间:2020-11-09 11:17:30

标签: reactjs typescript axios

我正在构建一个示例Web应用程序,并使用this虚拟数据api来获取数据。我正在使用React和axios进行api调用。响应数据如下所示:

api data looks like

所以我创建了以下接口来表示数据。

export type Category = {
    id: number,
    name: string
}

export type Product = {
    id: number,
    name: string,
    description: string,
    image: string,
    price: number,
    discount_amount: number,
    status: boolean,
    categories: Array<Category>
}
export type ProductResponse = {
    data: {
        code: number,
        data: Array<Product>
    }
}

我想按照以下方式获取数据并存储在类型化的状态变量中

const [products, setProducts] = useState<Array<Product>>([]);

  const fetchProducts = (): void => {
    const productUrl = "https://gorest.co.in/public-api/products";
    axios.get<ProductResponse>(productUrl).then((res) => {
      setProducts(res.data.data);
    });
  };

  useEffect(() => {
    fetchProducts();
  }, []);

存在类型错误

/home/ravinda/myjunkbox/react/react-redux-cake-shop-ts/src/components/Products.tsx
TypeScript error in /home/ravinda/myjunkbox/react/react-redux-cake-shop-ts/src/components/Products.tsx(12,19):
Argument of type '{ code: number; data: Product[]; }' is not assignable to parameter of type 'SetStateAction<Product[]>'.
  Type '{ code: number; data: Product[]; }' is not assignable to type '(prevState: Product[]) => Product[]'.
    Type '{ code: number; data: Product[]; }' provides no match for the signature '(prevState: Product[]): Product[]'.  TS2345

    10 |     const productUrl = "https://gorest.co.in/public-api/products";
    11 |     axios.get<ProductResponse>(productUrl).then((res) => {
  > 12 |       setProducts(res.data.data);
       |                   ^
    13 |     });
    14 |   };
    15 |

我想我正在尝试从响应中提取乘积数组,并将其设置为状态变量。我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

基于给出的错误,我认为您的结果缺少额外的.data。为了访问Axios的response中的值,您需要做一个.data,对于您的情况,.data将给您ProductResponse

const fetchProducts = (): void => {
    const productUrl = "https://gorest.co.in/public-api/products";
    axios.get<ProductResponse>(productUrl).then((res) => {
      setProducts(res.data.data.data);
    });
  };

res.data应该给您ProductResponse

res.data.data应该给您

{
  code: number,
  data: Array<Product>
}

res.data.data.data应该给您Array<Product>,与您在useState中指定的类型相同。