0

enter image description hereI am trying to make an axios error handler in my React application. In cases of error catching, I return a function, which in turn returns an array. But when I try to access the array, I get react error TypeError: Cannot read properties of undefined (reading 'join')

My error handler code:

  export default function requestErrorsHandler(error) {
  let errors = [];
  if (error.response) {
    if (error.response.status === 404) {
      errors = error.response.data.errors;
      return errors;
    }
    errors.push('The server was unable to process the request');
    return errors;
  } if (error.request) {
    errors.push('Failed to get response from server. Try again');
    return errors;
  }
  errors.push(error.message);
  return errors;
}

The function in which I make an axios request:

  export const getUser = async (userName) => {
  try {
    const response = await server.get(`${USER}/${userName}`);
    const user = response.data;
    return user;
  } catch (err) {
    return requestErrorHandler(err);
  }
};

The function in which I check for errors in the request. This is where I get the error:

    useEffect(async () => {
    const userData = await getUser(params.username);
    if (!userData) {
      return setError(userData.join('\n'));
    }
    ...
    return setError(null);
  }, []);

Error text Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'join') refers to this line: return setError(userData.join('\n'));

if you print the call to the error handler function to the console, then I get undefined. But I don’t understand why. My handler doesn't need to be asynchronous

Tom
  • 83
  • 1
  • 10
  • 1
    Don't use async functions as the `useEffect` callback. See [React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing](https://stackoverflow.com/q/53332321/283366) – Phil Nov 22 '21 at 05:41
  • 1
    `if (!userData)` checks if `userData` is _falsy_. You don't want to be trying to call `userData.join()` if that is true – Phil Nov 22 '21 at 05:42
  • @Phil, but I need to get the error text from the request – Tom Nov 22 '21 at 05:50
  • Then I suggest you have your `requestErrorsHandler` return a rejected promise (eg `Promise.reject(errors)`) or simply throw an error. Right now, your return value is ambiguous making it harder to identify errors – Phil Nov 22 '21 at 05:58

0 Answers0