Reputation:
I'm trying to register a user but whenever I do I get an error, the same one that's in the title. I'm not sure if I should be defining data or not but I'm pretty stuck here.
auth/register.js
import axios from 'axios';
import { setAlert } from './alert';
import {
REGISTER_SUCCESS,
REGISTER_FAIL
} from './types';
// Register User
export const register = ({ name, email, password}) => async dispatch => {
const config = {
headers: {
'Content- Type': 'application/json'
}
}
const body = JSON.stringify({ name, email, password });
try {
const res = await axios.post('/api/users', body, config);
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
} catch (err) {
const errors = err.response.data.errors;
if (errors) {
errors.forEach(error => dispatch(setAlert(error.msg, 'danger')));
}
dispatch({
type: REGISTER_FAIL
});
}
}
any help will be appreciated.
Upvotes: 1
Views: 231
Reputation: 202836
It seems the res.response.data.errors
access in the catch
block is throwing a new error that isn't being caught by your UI code.
While you should strive to write defensive UI code around asynchronous logic that is potentially rejected, I suggest using the Optional Chaining operator here to iterate over the errors array if it exists (i.e. if you can access that deep into the error object).
try {
const res = await axios.post('/api/users', body, config);
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
} catch (err) {
err.response?.data?.errors?.forEach(
error => dispatch(setAlert(error.msg, 'danger'))
);
dispatch({
type: REGISTER_FAIL
});
}
Upvotes: 1