React-Query how to get error message from onError callback?

Viewed 1386

I have small application where I am using React-Query, The problem is that when I try to activate onError callback, React Query first time checks onSuccess callback Even when the post request data is incorrect, and throws an error

TypeError: Cannot destructure property 'token' of 'data' as it is undefined. at Object.onSuccess

But actual API response is {response: null, error: "Unauthorised"} error: "Unauthorised" response: null

My problem is that I can't access error response from onError callback, What am I doing wrong?

/**
 * /* eslint-disable
 *
 * @format
 */

import { useMutation } from 'react-query';
import { useNavigate } from 'react-router-dom';
import AuthController from '../../../controller/auth';
import { useToasts } from 'react-toast-notifications';

const Login = () => {
  return AuthController.Login('user4', 'wrongpass');
};

export default function useUserLogin(setCheckTokenStatus) {
  const { addToast } = useToasts();
  const navigate = useNavigate();
  return useMutation(Login, {
    onSuccess: (data) => {
      console.log('succ');
      let {
        token,
        tokenExpiresAt,
        user: { firstname }
      } = data;
      setCheckTokenStatus(token);
      localStorage.setItem('idToken', JSON.stringify(token));
      localStorage.setItem('expires', JSON.stringify(tokenExpiresAt));
      navigate('/dashboard', {
        replace: true
      });
      addToast(`hello ${firstname}!`, { appearance: 'success', autoDismiss: true, autoDismissTimeout: 3000 });
    },
    onError: (error) => {
      console.log(error);
      addToast(`error: ${error}`, {
        appearance: 'error',
        autoDismiss: true,
        autoDismissTimeout: 3000
      });
    }
  });
}

/** @format */
//AuthController
import myAPI from '../../config/api/index';

export default class AuthController {
  static async Login(mobile, password) {
    let data = {
      mobile,
      password,
      role: 1
    };
    try {
      const response = await myAPI.post(`/login`, data);
      return response.data;
    } catch (err) {
      console.log('error occured');
    }
  }
}

0 Answers
Related