How can I display nested API error messages in my React component?

My React login form doesn’t render nested API error messages for empty fields. I need errors shown for email and password input.

import React, { useState } from 'react';
import axios from 'axios';

function SignInForm() {
  const [credentials, setCredentials] = useState({ email: '', password: '' });
  const [errMsgs, setErrMsgs] = useState({});

  const handleInput = (e) => setCredentials({ ...credentials, [e.target.name]: e.target.value });

  const processLogin = async (e) => {
    e.preventDefault();
    try {
      await axios.post('/api/login', credentials);
    } catch (error) {
      setErrMsgs(error.response.data.errors);
    }
  };

  return (
    <form onSubmit={processLogin}>
      <input name="email" type="email" value={credentials.email} onChange={handleInput} placeholder="Email" />
      <div>{errMsgs.email}</div>
      <input name="password" type="password" value={credentials.password} onChange={handleInput} placeholder="Password" />
      <div>{errMsgs.password}</div>
      <button type="submit">Sign In</button>
    </form>
  );
}

export default SignInForm;

I had a similar problem last year when working on a profile edit form. My solution involved writing a helper function that traverses the nested error object and dynamically assigns each error message to its corresponding form field. This approach made my error handling much more robust and allowed me to scale better when new fields were added. Errors were flattened before setting state, enabling the component to render them without device-specific checks. Experimenting with optional chaining also helped in avoiding undefined values during rendering.