In React, how do I handle errors coming back from the server?

ipenguin67

I have a signup form in my app that submits data to the my backend server, with a Redux thunk that calls my API and handles the returned data. Right now it only actually catches errors that occur within React/Redux. If the server returns an error, my action creator thinks the error is part of a user record and authenticates my "user", even if I submitted an empty form.

My handleSubmit function (extracted from my AuthForm component):

 const handleSubmit = e => {
    e.preventDefault();
    onAuth(formType, state);
    setState(formType === 'login' ? initialStateLogin : initialStateSignup);
    history.push("/");
  }

My onAuth function (which maps to my authUser Redux thunk):

export function authUser(type, userData) {
  return dispatch => {
      return apiCall("post", `/users/${type}`, userData)
        .then(({ jwt, ...user }) => {
          console.log(jwt, user)
          localStorage.setItem("jwtToken", jwt);
          setAuthorizationToken(jwt);
          dispatch(setCurrentUser(user));
          dispatch(removeError());
        })
        .catch(err => {
          console.log(err);
          dispatch(addError(err.message));
        });
  };
}

My apiCall helper function:

export async function apiCall(method, path, data) {
  try {
    const res = await axios[method.toLowerCase()](`${API_PATH}${path}`, data);
    return res.data;

  }
  catch(err) {
    console.log(err);
    return err.response.data || "An unknown error occurred";
  }
}

If I submit an empty form, my Redux state looks like this:

currentUser {
  isAuthenticated: true,
  user: {
    error: {
      message: "Could not create user. Please modify parameters and try again."
    }
 }
}
thedude

You are catching the API calls' erros. This causes your catch callback to never fire. Remove the try/catch block in apiCall.

Alternatively, you can return a Promise.reject() with the error data.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How should I handle an errors from server in Ember.js?

How do I handle errors from cleanup / destroy functions

How do I parse an object coming back from AWS SES SDK in JavaScript?

How do I make OS X set the terminal title back to the original title when coming back from ssh?

How do I handle Import Errors?

How do I handle errors in a deferred function?

How do I handle errors with promises?

How do I handle JavaScript Fetch errors?

How do I handle RapidXml errors?

How do I handle transaction errors?

How Do I Handle Errors Globally in TestCafe

How do I handle stripe errors for "redirectToCheckout"?

How do i handle errors in Dio package

How do I navigate from a React Child route back to a parent

How do I view a request coming into my Postman mock server?

(Discord PY) How do I handle slash command errors from different cog files?

How do I handle errors in a function called from a route handler in Express, NodeJS?

How do I handle errors from libc functions in an idiomatic Rust manner?

How do I handle exceptions when passing properties back from one method to another

How can i display images in React coming from api

How to deal with errors coming from ansible roles

How to restrict errors coming from iframe - htaccess

How to know coming back from Facebook?

How to handle when there is no react from server nodejs?

How can I handle the back button in React Native?

How do I receive the data coming from IBs API in Python?

How to properly handle errors on the server?

How do I handle errors in passport.deserializeUser()?

How do I handle errors in a worker pool using WaitGroup?