Home > Blockchain >  How to handle error in axios API at frontend
How to handle error in axios API at frontend

Time:06-22

I am using react-tool-kit (slice). This is for changing passwor form. The api is working well and error message shows at console. I want to know how to show up error or success message at page that user can check the message. The message show up at only console.

Please help me. Thank you in advance

// related code in redux slice 
const initialState = {
  isLoading: false,
  error: {
    status: '',
    message: null,
  },
const slice = createSlice({
  name: 'account',
  initialState,
  reducers: {
    hasError(state, action) {
      state.isLoading = false;
      state.error = action.payload;
    },

// call api 
   export function changePassword(changePasswordData) {
  return async () => {
    try {
      const accessToken = localStorage.getItem('accessToken');
      const userId = getUserIdFromToken(accessToken);

      const responseStatus = await axios.put(PATH_SERVER_API.accounts.changePassword(userId), changePasswordData);
      // dispatch(slice.actions.changePasswordSuccess({ status: responseStatus.status, message: responseStatus.data }));
      console.log(responseStatus);
      console.log(changePasswordData);
    } catch (error) {
      dispatch(slice.actions.hasError({ status: error.status, message: error.response.data.message }));
      console.log(error.response.data.message, error.status);
    }
  };
}

//  this is change password form - I think I have to do someting in here. but I don't know
// when user press onsubmit button then changePassword function run from slice 
// function is working. I only need to know show up success and error message to user
const onSubmit = async (data) => {
    try {
      dispatch(changePassword(data));
      reset();
 
    } catch (error) {
      console.error(error);
      reset(defaultValues);
    }
  };
  

CodePudding user response:

I updated the reducer file, try now. Let me if it worked!

// related code in redux slice 
const initialState = {
  isLoading: false,
  error: {
    status: '',
    message: null,
  },
const slice = createSlice({
  name: 'account',
  initialState,
  reducers: {
    hasError: (state, action) => {
      const {status, message} = action.payload;
      state = {
        isLoading: false,
        error:{
          status,
          message
        }
      }
    },

// call api 
   export function changePassword(changePasswordData) {
  return async () => {
    try {
      const accessToken = localStorage.getItem('accessToken');
      const userId = getUserIdFromToken(accessToken);

      const responseStatus = await axios.put(PATH_SERVER_API.accounts.changePassword(userId), changePasswordData);
      // dispatch(slice.actions.changePasswordSuccess({ status: responseStatus.status, message: responseStatus.data }));
      console.log(responseStatus);
      console.log(changePasswordData);
    } catch (error) {
      dispatch(slice.actions.hasError({ status: error.status, message: error.response.data.message }));
      console.log(error.response.data.message, error.status);
    }
  };
}

CodePudding user response:

This is redux- slice code

import { createSlice } from '@reduxjs/toolkit';
import { dispatch } from '../store';
import { PATH_SERVER_API } from '../../routes/paths';
import axios from '../../utils/axios';
import { getUserIdFromToken } from '../../utils/jwt';

const initialState = {
  error: null,
  isLoading: false,
  user: {},
  userInfo: {},
  successMsg: { status: '', message: null },
};

const slice = createSlice({
  name: 'account',
  initialState,
  reducers: {
    hasError(state, action) {
      state.isLoading = false;
      state.error = action.payload;
    },

 
    //  changepassword form - response data save
    changePasswordSuccess: (state, action) => {
      const successMsg = action.payload;
      state.successMsg = successMsg;
    },
  },
});

// Reducer
export default slice.reducer;

// Api Call Functions


// change password api - put : http://localhost:8080/api/accounts/{userId}/change-password
export function changePassword(changePasswordData) {

  return async () => {
    try {
    // get user id 
      const accessToken = localStorage.getItem('accessToken');
      const userId = getUserIdFromToken(accessToken);

      const responseStatus = await axios.put(PATH_SERVER_API.accounts.changePassword(userId), changePasswordData);
      
      dispatch(
        slice.actions.changePasswordSuccess({ status: responseStatus.status, message: responseStatus.data.message })
      );
     
    } catch (error) {
      console.log('failure call');
      dispatch(slice.actions.hasError(error));   
    }
  };
}

This is form component

export default function AccountChangePassword() {
  const dispatch = useDispatch();
  const { enqueueSnackbar } = useSnackbar();
  const isMountedRef = useIsMountedRef();
  const { successMsg } = useSelector((state) => state.account);

  const ChangePassWordSchema = Yup.object().shape({
    currentPassword: Yup.string().required('Current Password is required'),
    newPassword: Yup.string()
      .matches(
        /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/,
        'Password must include 8 characters, at least 1 lowercase letter, 1 uppercase letter, a number and a symbol.'
      )
      .required('New Password is required'),
    confirmPassword: Yup.string()
      .required('Confirm password is required')
      .oneOf([Yup.ref('newPassword'), null], 'Passwords must match'),
  });

  const defaultValues = {
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
  };

  const methods = useForm({
    resolver: yupResolver(ChangePassWordSchema),
    defaultValues,
  });

  const {
    reset,
    setError,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = methods;

  const onSubmit = async (data) => {
    try {
      dispatch(changePassword(data));
      if (successMsg) {
        reset();
        enqueueSnackbar(successMsg);
      }
    } catch (error) {
      reset(defaultValues);

      if (isMountedRef.current) {
        setError('afterSubmit', { ...error, message: error.message });
      }
    }
  };

  return (
    <Card sx={{ p: 3 }}>
      <FormProvider methods={methods} onSubmit={handleSubmit(onSubmit)}>
        <Stack spacing={3} alignItems="flex-end">
          {!!errors.afterSubmit && <Alert severity="error">{errors.afterSubmit.message}</Alert>}
          <RHFTextField name="currentPassword" type="password" label="Current Password" />
          <RHFTextField name="newPassword" type="password" label="New Password" />
          <RHFTextField name="confirmPassword" type="password" label="Confirm New Password" />
          <LoadingButton type="submit" variant="contained" loading={isSubmitting}>
            Save Changes
          </LoadingButton>
        </Stack>
      </FormProvider>
    </Card>
  );
}

doesn't working at form page - success or error message not show up the page. I think that onsubmit function can;t get a message from redux. so how to get a message and display at form

  • Related