Home > Net >  How describe with typescript axios request
How describe with typescript axios request

Time:10-15

I have thunk action with axios request but it's failed when instead of request I get error because below my reducer wait for data with IUser types but instead got error messages from server

My code:

export const checkAuth = createAsyncThunk(
    `authService/checkAuth`,
    async (prevLocation:string) => {

        const response = await axios.get<IUser>('/api/auth/current')
        return {user:response.data, isAuth: true}
    }
)

Question: How correctly handle axios request, errors

CodePudding user response:

What you want to do with async/await code is to always implement try/catch blocks, so situations like that won't happen, and the error will be properly handled.

async () => {
  let response; // properly typed
  try {
    response = await axios.get<IUser>('/api/auth/current')
  } catch(ex) {
    console.log(ex) // handle exception
  }
}

You can now add proper logic to handle your error and return valid stuff :)

  • Related