Home > Net >  async await typescript react
async await typescript react

Time:09-13

I am using async and await for getting response from an api but when I using it with react type script it keeps

TS2339: Property 'email' does not exist on type 'AxiosResponse<any, any>'.

I am following a course but it seems he work in older version is there any way to achieve that

here is my function for submit form

const submitRegister = async (e: SyntheticEvent)=>{
    e.preventDefault();
    const { email:email } = await axios.post('http://lovalhost/8000');
}

any help will be appreciated

CodePudding user response:

'http://lovalhost/8000'

Do you mean 'localhost:8000'?

const { email:email } = await axios.post()

Here you are destructing the response for the email property. If you look at the actual response you will find that you are probably looking for response.data.email

Try using .then and .catch as well.

const email = await axios.post('http://lovalhost/8000').then(({data}) => data.email).catch(error => console.error(error))

CodePudding user response:

The response from await axiosPost(...) will be an object containing a data key that holds the data returned from the request.

const response = await axios.post('http://lovalhost/8000');
console.log(response.data.email) // this is where your email value will be (in case the request is succesful)

You can also let typescript know what your response data will look like, by adding the type to the call.

const response = await axios.post<{email: string}>('http://lovalhost/8000');

CodePudding user response:

You need to access the data object within the response as can be seen here https://axios-http.com/docs/res_schema

Try something like this:

const { data } = await axios.post('http://lovalhost/8000');
const { email } = data

or maybe store the response object because that will also have information about the response status etc.

try {
    const response = await axios.post('http://lovalhost/8000');

    if (response.status != 200) {
       // throw
    }

    const { email } = response.data
    return email
}
catch (ex) {
    console.error(ex)
}

  • Related