DevOverflow
DevOverflow

Reputation: 1712

How describe with typescript axios request

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

Upvotes: 0

Views: 564

Answers (1)

majkelS
majkelS

Reputation: 622

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

Upvotes: 1

Related Questions