How to handle error message from server in nextjs?
Answered
Sun bear posted this in #help-forum
Sun bearOP
I am using react query with nextjs. If i try to get the errors, from react query it says this: Property 'message' does not exist on type '{}'.ts(2339)
Answered by riský
try this... i added lots of
| undefined because your code had the ?.interface ErrorMessage {
response: {
data: {
message: string
} | undefined
} | undefined
}
const otpMutation = useMutation({
mutationFn: (data: string) => verifyOtp(data),
onError: (error: ErrorMessage)=>{
console.log(error?.response?.data.message, 'err')
}
});20 Replies
that is a typescript error...
if you share your code, i can sugest a way to make it not complain
Sun bearOP
error?response?.data.message
i get the error message like this, but that ts error would not allow me to build the code
i get the error message like this, but that ts error would not allow me to build the code
are you using typescript (.tsx) or javascript (.jsx)
Sun bearOP
const otpMutation = useMutation({
mutationFn: (data: string) => verifyOtp(data),
onError: (error)=>{
console.log(error?response?.data.message, 'err')
}
});
mutationFn: (data: string) => verifyOtp(data),
onError: (error)=>{
console.log(error?response?.data.message, 'err')
}
});
this should be easy then:
const otpMutation = useMutation({
mutationFn: (data: string) => verifyOtp(data),
onError: (error)=>{
const data = error?.response?.data as {message: string} | undefined
console.log(data?.message, 'err')
}
});this tells ts that data has message in data or is undefined
you can also just put
// @ts-expect-error on the line before to make it ignore the issues (not very recommended)Sun bearOP
now it says: Property 'response' does not exist on type '{}'.ts(2339)
ahh i thought the error was from diferent
try this... i added lots of
| undefined because your code had the ?.interface ErrorMessage {
response: {
data: {
message: string
} | undefined
} | undefined
}
const otpMutation = useMutation({
mutationFn: (data: string) => verifyOtp(data),
onError: (error: ErrorMessage)=>{
console.log(error?.response?.data.message, 'err')
}
});Answer
@riský you can also just put `// @ts-expect-error` on the line before to make it ignore the issues (not very recommended)
Sun bearOP
Yes. but linter will not allow me to do that.
@Sun bear Yes. but linter will not allow me to do that.
good on it 🙂 you can also disable that for the ignore line too
@Sun bear Let me just try it
how did it go?
Sun bearOP
It worked man.
Thanks. 😊
yay!
feel free to mess with the interface if and when you want to change how the types work