Search code examples
javascriptreactjsreact-hooksreact-toastify

Need to make React Toast in Catch Block Axios


Hi Every one I want to make a React-Toast notification for making catch but it not working

currently my function is something like this

const naviagte = useNavigate();
  const dispatch = useDispatch();
  const [inputs, setInputs] = useState({
    name: "",
    email: "",
    password: "",
    gender: "",
    type: "",
    id: "",
    birthday: "",
  });

  const [isSignup, setIsSignup] = useState(false);
  const handleChange = (e) => {
    setInputs((prevState) => ({
      ...prevState,
      [e.target.name]: e.target.value,
    }));
  };
  const sendRequest = async (type = "login") => {
    const res = await axios
      .post(`http://localhost:5000/api/user/${type}`, {
        name: inputs.name,
        email: inputs.email,
        password: inputs.password,
        gender: inputs.gender,
        birthday: inputs.birthday,
        type: inputs.type,
        id: inputs.id,
      })
      .then((res) => {
        if (res.status === 200) {
          ToastN(res.data.message, "success");
        }
      })
      .then(() =>
        dispatch(
          login({
            name: inputs.name,
            email: inputs.email,
            password: inputs.password,
            gender: inputs.gender,
            birthday: inputs.birthday,
            type: inputs.type,
            id: inputs.id,
            isloggedIN: true,
          })
        )
      )
      .then(() => naviagte("/Home"))
      .catch((res) => {
        if (res.status === 400) {
          ToastN(res.message, "warning");
        }
      });
    const data = await JSON.stringify(res.data);
    return data;
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (isSignup) {
      sendRequest("signup")
        .then(() =>
          dispatch(
            login({
              name: inputs.name,
              email: inputs.email,
              password: inputs.password,
              gender: inputs.gender,
              birthday: inputs.birthday,
              type: inputs.type,
              id: inputs.id,
              isloggedIN: true,
            })
          )
        )
        .then(() => naviagte("/Home"));
    } else {
      sendRequest("login");
    }
  };

The success is working fine, but not able to make error call not sure what is wrong. tried everything not sure what to do

or shall i add Formick for this ? any suggestions


Solution

  • the answer was i need to check Err.response instead of status as the status was present in response block. that why earlier i was getting undefined.