Beginner Professional
Beginner Professional

Reputation: 347

I get an error when I type-define the axios response

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

Upvotes: 1

Views: 511

Answers (3)

ghybs
ghybs

Reputation: 53280

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<Article[]>()

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
    })
  }
})

Upvotes: 0

g.p
g.p

Reputation: 370

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.

Upvotes: 1

Ron Newcomb
Ron Newcomb

Reputation: 3302

Usually promises can be typed thus:

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

Upvotes: 0

Related Questions