Home > Mobile >  I get an error when I type-define the axios response
I get an error when I type-define the axios response

Time:07-18

What we want to solve

I would like to retrieve a value using NewsAPI, but I do not know how to set the response type. Specifically, I think I need to set the type to an array of object types, but I don't know how to do that.

Code

type

export type AllNews = {
  status: string;
  totalResults: number;
  articles: [{
    source: {
      id: string;
      name: string;
    }
      author: string;
      title: string;
      description: string;
      url: string;
      urlToImage: string;
      publishedAt: string;
      content: string;
  }]
}


import axios from "axios"
import { AllNews } from "../../types/AllNews"

・・・
export const Top = () => {
   const [ news, setNews] = useState<AllNews>()

useEffect(() => {
 const getTopNews = () => {

    axios.get<AllNews>('https://newsapi.org/v2/top-headlines?country=us&apiKey=xxxxxx')
    .then((res) => {
      setNews(res.articles)

    })
  }
})

・・・

Response data to be acquired

CodePudding user response:

Assuming you are using latest version of axios, the response from axios is of type

export interface AxiosResponse<T = any, D = any>  {
  data: T;
  status: number;
  statusText: string;
  headers: AxiosResponseHeaders;
  config: AxiosRequestConfig<D>;
  request?: any;
}

https://axios-http.com/docs/res_schema

Try doing res.data.articles.

CodePudding user response:

Usually promises can be typed thus:

    .then<AllNews>((res) => {

CodePudding user response:

Your news state is a sub-object of AllNews type, which contains articles and metadata about the response.

Making a separate Article type, we could do:

export interface Article {
  source: {
    id: string;
    name: string;
  };
  author: string;
  title: string;
  description: string;
  url: string;
  urlToImage: string;
  publishedAt: string;
  content: string;
}

export type AllNews = {
  status: string;
  totalResults: number;
  articles: Article[];
}

export const Top = () => {
   const [ news, setNews] = useState<Articles[]>()

useEffect(() => {
 const getTopNews = () => {

    axios.get<AllNews>('https://newsapi.org/v2/top-headlines?country=us&apiKey=xxxxxx')
    .then((res) => {
      setNews(res.data.articles) // news is set to only the articles, not the full AllNews

    })
  }
})
  • Related