1

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

1
  • There's probably a data property IIRC, so it would look like const { data: { email } } = ... Commented Sep 13, 2022 at 14:22

3 Answers 3

1

'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))
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.