What is the proper type declaration for incoming data from the backend in my TypeScript code when using axios?

In the TypeScript code snippet provided, the type for 'e' (used in the function for form submission) has been figured out. However, a question arises if this type declaration is correct. Additionally, in the catch block, the type "any" is used for an error. What would be the ideal type for handling errors, and what type should be declared for JSON data received from the backend?

const ResetPassword = async (e : React.FormEvent<HTMLFormElement>) =>  {
        e.preventDefault()
        try {
        if (info.password !== info.confirm_password) {
            toast.error("Password don't match")
        }
        else {
            interface res {
                message : string;
                success : boolean;
            }
            const response = await axios.post('/api/resetpassword',
            {
                token : info.token,
                password : info.password
            })

            const responseData :  res = response.data

            if(responseData.success) {
                toast.success(responseData.message)
                router.push('/login')
            }
            else {
                toast.error(responseData.message)
            }
        }
        } catch (error : any) {
            toast.error("Something went wrong")
        }


    }

Is there a more efficient way to write the above code for better performance?

Answer №1

If you want to utilize both AxiosResponse and AxiosError from the axios library, you need to ensure that you have properly installed the types package @types/axios

import axios, { AxiosResponse, AxiosError } from 'axios';

try {
    const response: AxiosResponse<ExpectedType> = await axios.post('/api/resetpassword', {
        token: info.token,
        password: info.password
    });
} catch (error: AxiosError) {
    // handle error
}

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

What is the most effective method for dynamically showcasing buttons in AngularJS?

Hello all, I'm currently learning AngularJS and I was wondering if anyone could recommend the simplest and most effective method for dynamically displaying links from AngularJS to HTML. I am looking to display a variable number of buttons in my HTML ...

Building Firestore subcollections with the latest WebSDK 9: A step-by-step guide

I'm looking to create a subcollection within my document using the webSDK 9, specifically the tree-shakable SDK. While I have come across some solutions, they all seem to be outdated and reliant on the old sdk. Just for context, I am working with Ne ...

Firebase has flagged the Google Authentication process with a message stating: Entry denied: The request made by this application

I have connected my domain to Firebase authentication and granted authorization for authentication access. If you want to test it out, feel free to visit this link signInWithPopup(auth, provider) .then((result) => { // This provides a Google Acc ...

Initiate a timer with intervals of 3 seconds upon reaching a designated section in a React application

useEffect(() => { console.log(window.scrollTo) console.log(textInput.current.offsetTop); }, [textInput,]) click here for more information check out the bottom of this page for a similar countdown feature - any ideas on how to implement it? ...

eliminating labels from a string through recursive method

One of my challenges involves developing a function that can remove tags from an input string. For example: '<strong>hello <em>my name <strong>is</strong> </em></strong>' The desired result should be: &apos ...

Converting Dates with Ractive.js

Is there a way to transform the Epoch time value retrieved from a JSON endpoint into a readable time string format such as "Tue 19 Jan 11:14:07 SGT 2038" without relying on external libraries like moment.js? var ractive = new Ractive({ el: '#cont ...

System CSS modules do not work correctly with Reactjs, CRA, TS, and Carco when using Less

Issues have arisen with the CSS module system in my project. Below are snippets from various code files and configurations: react-app-env.d.ts, craco.config.js, CircleButtonWithMessage.module.less, CircleButtonWithMessage.tsx, as described below: //react-a ...

Angular & Loopback: The function User.login is not recognized

Today, I encountered an error while attempting to execute the Login function in Ionic. An error message popped up stating: TypeError: User.login is not a function (found in controller.js). Here's a snippet from my controller.js : angular.module(&ap ...

What is the process for accessing a URL using a web browser and receiving a plain text file instead of HTML code?

Hello there! I've created a simple HTML file located at that can display your public IP address. If you take a look at the code of the page, you'll notice that it's just plain HTML - nothing fancy! However, I'm aiming for something mo ...

Is there a way to recover a deleted element from an array?

I have a list of user cards, and my task is: Clicking the "undo" button: will restore the last card that was deleted (using an array) Question 1: How can I create an array from the displayed cards list? Question 2: How do I restore the last deleted card? ...

Issues with the typings for the toPromise function in WebStorm have been identified

I'm encountering an issue with WebStorm not recognizing the typings for the toPromise function on 'rxjs', despite having updated it. Is there a way I can troubleshoot this and fix it? Strangely, the code still runs successfully despite the ...

How to Change a Property in a Child DTO Class in NestJS with Node.js

I am working with enums for status: export enum Status { Active = "Active", Inactive = "Inactive", } Additionally, I have a UserStatus enum: export enum UserStatus { Active = Status.Active, }; There is also a common dto that inc ...

PHP: variables malfunctioning post implementation of "if" statement

Recently, I encountered a strange issue while working on a database processor. After processing the login information, the variables containing the data seemed to disappear and any subsequent actions within the "if" statement, which verified the login info ...

Developing a dynamic API route in Next.js: A step-by-step guide

My goal is to create a dynamic route in the api folder for processing GET requests. Initially, everything works smoothly with the route api/[product]. const baseUrl ='https://myUrl' const { product } = req.query const url = `${baseUrl}/${pro ...

The challenge with linking within Layerslider

Having some trouble with an external link to a specific layerslider slide (html version, NOT wordpress). Here is the webpage in question: After reaching out in the support forum, I was advised to use this javascript: <a href="javascript:void(0);" onc ...

Collaborative Artistry: Using HTML5, JavaScript, and Node.js for Multiplayer

Creating a multiplayer drawing application for touch-enabled devices has been a challenge. I have utilized Node.js with Socket.io to draw points on a canvas, but there's an issue with the touchend event not resetting properly. To illustrate, take a l ...

Executing a single Function within the UseEffect Hook

Can anyone assist me with solving this code puzzle? I have a carousel element that includes icons for moving to the previous and next slides. Whenever these icons are clicked, a specific function needs to be triggered within the useEffect() hook. The spec ...

Why does HttpClient in Angular 4 automatically assume that the request I am sending is in JSON format?

Currently, I am working with Angular 4's http client to communicate with a server that provides text data. To achieve this, I have implemented the following code snippet: this.http.get('assets/a.txt').map((res:Response) => res.text()).s ...

`Modified regions determined by cursor location`

I am working with a split layout featuring two columns, and I need the ability to make each column separately scrollable. Due to using a specialized scroll-to function, I cannot use overflow-y: scroll; or overflow: auto;. I am looking for alternative solut ...

Can you suggest a simple method for implementing the "componentDidUpdate()" lifecycle method using just JavaScript?

I've been curious about replicating the componentDidUpdate() lifecycle method in JavaScript on my own. It got me thinking, how did React and Vue.JS create their own lifecycle methods? I attempted to study the minified version of Vue.JS but found it qu ...