0

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,

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Will this creates li items? I want to show each error in separate line as li items.
@rjcode Yes, I've added an example. You get an array of errors and print each error in li by using map
0
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 });
  ...
};

1 Comment

Thank you, this will create a long string of joining all errors, can you help how can i create it as list items? So i can show each error in separate line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.