I am having troubles trying to output my errors in react. the data is coming from an external API, and is formatted like so;
{
"message": "The given data was invalid.",
"errors": {
"name": [
"The name field is required."
],
"address": [
"The address field is required."
],
"postcode": [
"The postcode field is required."
]
}
}
My page which returns the API data and the error component looks something like this;
const ShowData = () => {
const [errorData, setErrorData] = useState([]);
const onSubmit = handleSubmit(async ({ name, address, postcode }) => {
if (errorData) setErrorData([]);
try {
// Call API and process here
} catch (error) {
setErrorData(error.data);
}
});
return (
<div>
{errorData && !Object.keys(errorData).length == 0 &&
<ErrorComponent errorData={errorData} />
}
</div>
)
}
export default ShowData;
class ErrorComponent extends Component {
render() {
const errorData = this.props.errorData;
return (
<div>{errorData.message}</div>
<ul>
{errorData.errors.map(error => {
<li>{error}</li>
})}
</ul>
)
}
}
export default ErrorComponent;
The error i am receiving is;
errorData.errors.map is not a function
The following is what i am trying to achieve;
<div>The given data was invalid.</div>
<ul>
<li>The name field is required.</li>
<li>The address field is required.</li>
<li>The postcode field is required.</li>
</ul>
errorData.errorsis an object, not an array