Home > database >  How can I create an interface for API data in typescript?
How can I create an interface for API data in typescript?

Time:01-30

So I'm getting data from TMDb API(movies) and my App.js looks like this:

const App = () => {

  const [movies, setMovies] = useState<MovieType[]>([]); //state for setting movies to api data

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

  async function fetchMovies() {   //function for fetching data
    try{
      let apikey = '{api_key}';
      let url: string = 'https://api.themoviedb.org/3/discover/movie?sort_by=popularity.desc&api_key=';
      url = url   apikey;
      const response = await axios.get<MovieResults[]>(url);
      setMovies(response.data.results);    //and here I get an error: Property 'results' does not exist on type 'MovieResults[]'
    }catch(e){
      alert(e);
      console.log(movies);
    }
}

  return (
    <div className="App">
      <Header/>
      <Hero movies={movies}/>
    </div>
  );
}

My types and interfaces:

export type MovieType = {
        vote_average: string,
        title: string,
        tagline: string,
        date: string,
        img: File,
    };

export type MovieResults = {
    results: MovieType[],
};

export interface MovieProps {
     movies: MovieType[],
      };

As you can see, I have types and interfaces, I created MovieType for passing props, and MovieResults for getting results from API. But I have an error when I try to set movies to api data: Property 'results' does not exist on type 'MovieResults[]' It's weird, because I actually have "results" property in MovieResults.

CodePudding user response:

I think you meant to do axios.get<MovieResults>. If you do axios.get<MovieResults[]>, it will expect an array of MovieResults which I think is not what you want.

If you use MovieResults[] as type, you are basically expecting the data to be the following

[
  { results: ... }, 
  { results: ... }, 
  { results: ... }, 
  .
  .
  .
]

So, you are trying to read results from an array, which is not defined.

But, if you use MovieResults as type, the format of data will be the following

{
  results: ...
}

Here, you are reading results from an object.

  •  Tags:  
  • Related