I am trying to handle an array of errors on the front end side and display them on the page. I am getting the fields that user has entered from the backend and trying to map them out. However, backend params are being returned in camelcase. Please see below:
I want to render: The input field(s) for email, favorite sport, gpa score are unacceptable
But I am seeing
The input field(s) for email, favoriteSport, gpaScore are unacceptable
Is there any way I can map the name of the params to a custom name?
Here is my code:
Array.isArray(errors) ? `The input fields for ${errors.map(item => item.param)} are unacceptable`
Any way i could map the param names to my own liking?
CodePudding user response:
const mapper = (item) => {
return {
gpaScore: 'GPA Score',
favoriteSport: 'Favorite Sport',
}[item.param] || 'Unknown property'
}
return `The input fields for ${errors.map(item => mapper(item)).join(', ')} are unacceptable`
CodePudding user response:
This is where you could use something like react-intl to format messages but in general, you'd need something that turns programmatic keys into user-friendly messages
const t = {
email: "email",
favoriteSport: "favourite sport",
gpaScore: "GPA score"
}
const fields = errors.map(({ param }) => t[param] ?? param)
const message = `The input fields for ${fields.join(", ")} are unacceptable`