Home > database >  showing error message returned from server validation in react
showing error message returned from server validation in react

Time:02-11

Below is axios request sent to server for data submit and in return I am getting validation errors if any,

  const storeExpense = async (expenseData) => {

    const response = await axios.post('/api/expenses/store/', expenseData).catch(function (error) {
      if (error.response) {
        return error.response.data;

      } else if (error.request) {
        console.log(error.request);
      } else {

        console.log('Error', error.message);
      }
    });
    return response;
  }

In another component, I storing return in variable,

const response = await storeExpense(values)

if('errors' in response)
{
  setValErrors(Object.values(response))
  setStatus({ success: false });
  setErrors({ submit: response.errors });
  setSubmitting(false);
  setRequestStatus(true)
}

Below is the return response, it's an array and with objects.

Array [ "The given data was invalid.", {…} ]
​
0: "The given data was invalid."
​
1: Object { expense_description: (1) […], accountcustomtype_id: (1) […], expense_date: (1) […], … }
​​
accountcustomtype_id: Array [ "Expense account is required." ]
​​​
​​expense_amount: Array [ "Expense amount is required." ]
​​
expense_date: Array [ "Expense date is required." ]
​​
expense_description: Array [ "Expense description is required." ]
​​
paymentoption_id: Array [ "Payment with is required." ]
​​
taxgroup_id: Array [ "Tax is required." ]
​​

How can I print each validation error messages? with .map()?

Thank you,

CodePudding user response:

const response = await storeExpense(values)

if('errors' in response){
  const errorsList = responce.errors[1];
  const errors = Object.keys(errorsList).map(k =>errorsList[k].join(''))
  setErrors({ submit: errors });
  ...
};

CodePudding user response:

Updated after @rjcode comment

You can try to get all errors as an array like this:

const errorsArr = [].concat(...Object.values(responce[1]))

And after that you are able to print all errors from this array in <li>, as an example:

const responce = ["The given data was invalid.",
  {
    expense_description: ["Expense account is required."],
    accountcustomtype_id: ["Expense account is required."],
    expense_date: ["Expense date is required."],
    paymentoption_id: ["Payment with is required."],
    taxgroup_id: ["Tax is required."]
  }
]

const errorsArr = [].concat(...Object.values(responce[1]))

class LoopThrough extends React.Component {
  render() {
    return (
      <div>
        {this.props.errors.map(error => (
          <li key={error} >{error}</li>
        ))}
      </div>
    );
  }
}

ReactDOM.render(
  <LoopThrough errors={errorsArr} />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container">
</div>

  • Related