Tips for creating TypeScript types for Axios.get with an external API

Seeking guidance on parsing data obtained from an axios.get request to the TMDB-API, a movie database.

Here is a simplified version of the JSON structure returned by the API:

{
    data: {
        results: [
            {
                name: 'Free Guy'
                poster_path: "/yc2IfL701hGkNHRgzmF4C6VKO14.jpg"
            },
            {
                name: 'Squid Game'
                poster_path: "/uu4TgyyW259aOZHN0Ew4TEfjnUG.jpg"
            },
        ]
    }
}

My state is defined as follows:

interface MovieType {
    name: string
    poster_path: string
}

const [movies, setMovies] = useState<MovieType[] | []>([]);

However, when attempting to retrieve and set the results from the get-request, I encounter the TypeScript error:

Property 'results' does not exist on type 'DataMovieType'.ts(2339)

interface DataMovieType {
    data: {
        results: MovieType[]
    }
}

const request = await axiosInstance.get<DataMovieType>(fetchUrl);
setMovies(request.data.results);

I have explored alternative interfaces for DataMovieType but have not found a solution yet.

If you need more information or have any insights, please let me know. Appreciate your help!

Thank you, [name]

Answer №1

Solution provided by @brc-dd

After reviewing the official documentation, it seems that there is no 'data' field in JSON. The type or interface (T) you need to specify for axios.get should match the structure of response.data rather than the actual response itself.

My mistake was including 'data' in my type definition. I updated it as shown below, and it worked successfully:

interface DataMovieType {
    results: MovieType[]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The compilation time of Webpack and Angular 2

My compile time is currently at 40 seconds and I'm looking for ways to speed it up. I attempted setting the isolatedModules flag to true in the configuration but encountered an error: error TS1208: Cannot compile namespaces when the '--isolated ...

React Vite is encountering an error when processing CSS module files with the message 'Unable to locate module or its corresponding type declarations.'

After importing NavbarSample.module.css file, the content inside includes CSS styling for a .navbar class with specific properties like width, height, padding, display, flex direction, and border. However, when attempting to import this CSS module file in ...

Is there a way to customize the text color beneath a Doughnut chart using react-chartjs-2?

Currently, I am utilizing the Doughnut feature from the react-chartjs-2 library and I have a specific request. My goal is to change the color of the text beneath the graph to white because it is difficult to read against the current background (please refe ...

After deploying my Next.js app to Vercel, I encountered a problem where the rss.xml file in the public folder was returning

I have successfully created an rss.xml file and wrote it using fs.writeFileSync. It works fine when viewed locally, but on vercel, the build fails with an error stating "no such file or directory ./public/rss.xml." If I comment out the fs.writeFileSync li ...

Tips for capturing the output of a dynamically rendered component in Angular 8

I need to capture the output from a rendered component using ViewChild. The content of ViewChild is displayed after an ngIf condition is met. Here is the template code: <div *ngIf="isModalVisible" class="modal" tabindex="-1" role="dialog"> <di ...

When defining a component decorator in Angular 2, mixing tabs and spaces can lead to an unhandled exception

After refactoring my Angular 2 component code and adding some tabulations, the code suddenly stopped working. Surprisingly, when I removed the tabs (spaces), it started working again. @Component({ templateUrl : './app.component.html', styl ...

The Jest test encounters failure when attempting to use an absolute path to load an SVG image

Currently, I am developing a Typescript React application using Vite. To test my app, I have implemented Jest and babel. An important aspect of my setup is the use of absolute paths throughout the entire application. Interestingly, when I run tests with r ...

Attempting to retrieve data either by code or with a WHERE condition proves unsuccessful as the data retrieval process yields no results

Seeking assistance with my Angular project that is utilizing a Node.js server and MSSQL express. I am having trouble retrieving data using a WHERE condition in my code. Any help in identifying the missing piece or error would be appreciated. Thank you. // ...

The 'prop' property is not found in the 'A | B' type

When retrieving data from a URL, if a specific condition is met, the information will be loaded into either type B or its superclass A. However, an issue arises when the data is loaded into B and TypeScript fails to recognize its properties. The code sni ...

Angular 2 components not properly handling two-way binding errors

Exploring how to achieve two-way binding in Angular 2, I am currently working with the following parent component setup: app.component.html: <child [(text)]="childText" (textChanged)="textChanged($event)"></child> <span>{{childText}}< ...

Leveraging the 'window' object as a dependency in the useEffect hook within NextJS

I'm encountering an issue where I need a function to run when the type of window.performance.getEntriesByType("navigation")[0].type changes. I attempted to use useEffect for this purpose, but it resulted in a 'window is not defined&apos ...

Creating dynamic routes in Next.js and handling 404 redirects when the route is not found

Currently, I am working on creating a dynamic route using Next.js 13 within the app folder. My goal is to define some static routes and if the slug does not match what I have specified, it should return a 404 page. I had previously implemented this succes ...

Leveraging TypeScript enums in conjunction with React to anticipate a string prop

Trying to enforce strict typing for a Button component in React. How can I ensure a prop has a specific string value? The current effort yields Type '"primary"' is not assignable to type 'ButtonLevel' enum ButtonLevel { Primary = ...

Angular2: Form reset triggers row deletion

In my system, there is a table displaying student data with CRUD functions. Each row in the table has an Edit button. <table class="table table-bordered table-striped"> <thead class="studentHeader"> <tr> ...

Angular: What is the best way to retrieve the class name in the app-root from a local component?

My website consists of three main pages and multiple child pages. Each child page inherits its style from the parent CSS. country.routes.ts ... path: '', children: [ { path: '/country', component: CountryComponent ...

Error message: The token signature is invalid when verified on jwt.io

Has anyone else encountered similar errors while attempting to decode their next-auth.session-token on jwt.io? I followed a tutorial and attempted to paste my session token into jwt.io to view it, but all I received was an error stating "Invalid signature" ...

Integrating the Facebook Messenger Chat Plugin into your NextJS website allows

I'm working on integrating a Facebook Messenger chatbot into my NextJs app, but I'm facing an issue during the setup. Facebook is requesting me to add a code snippet to my website. <!-- Load Facebook SDK for JavaScript --> <div id=" ...

Getting a URL path in Next.js without relying on the Link component when the basePath is configured

Base Path from the next.js documentation states: For instance, by setting basePath to /docs, /about will automatically transform into /docs/about. export default function HomePage() { return ( <> <Link href="/about"> ...

Using TypeScript, you can pass an object property name as a function argument while ensuring the type is

How can I define a type in a function argument that corresponds to one of the object properties with the same type? For instance, if I have an object: type Article = { name: string; quantity: number; priceNet: number; priceGross: number; }; and I ...

What is the best way to extract a specific property from an object?

Consider the following function: getNewColor(): {} { return colors.red; } Along with this object: colors: any = { red: {primary: '#ad2121',secondary: '#FAE3E3'}, blue: {primary: '#1e90ff',secondary: '#D1E8FF&apos ...