0

I want to put the errors returned from making an axios API call, to the React state. Here is the React component.

export const formDataObject = yup.object({
    name: yup.string()
        .max(32, "No more than 32 characters for category name")
        .required("The category name is required")
});

const NewCategory = () => {
    const navigate = useNavigate();
    const [errors, setErrors] = useState([]);
    const [data, setData] = useState({
        name: ""
    });

    const changeValue = (field, val) => {
        const newData = { ...data };
        newData[field] = val;
        setData(newData);
    };

    const validateSubmit = (e) => { 
        e.preventDefault();

        formDataObject
            .validate(data, { abortEarly: false })
            .then((responseData) => {
                setErrors([]);

                axios.post("http://bigblog.com/api/v1/categories/store", {
                    id: null,
                    name: data.name
                })
                .then(function(response) {
                    alert("Success! New Category Added");
                    navigate("/dashboard/categories", {replace: true});
                })
                .catch(function(err) { 
                    console.log(err.response.data.errors);
                });
            })
            .catch((err) => { 
                setErrors(err.errors);
            });
    };

    return (
        <>
            <h5 className="card-title">Categories :: New Category</h5>
            <div>
                <Link className="btn btn-outline-dark btn-md w-25" role="button" to="/dashboard/categories">Categories</Link>
            </div>

            <hr />
            <div className="container">
                <div className="row">
                    <div className="col-lg-8">
            
                        <form onSubmit={validateSubmit}>
                            <div className="form-group">
                                <label htmlFor="name">Name</label>
                                <input
                                    id="name"
                                    type="text"
                                    name="name"
                                    value={data.name ?? ""}
                                    className="form-control form-control-lg"
                                    placeholder="Enter a new category name"
                                    onChange={(e) => changeValue("name", e.target.value)}
                                />
                            </div>

                            <div className="form-group form-check">
                                <input 
                                    className="form-check-input" 
                                    type="checkbox" 
                                    value="" 
                                    id="active" 
                                />
                                <label htmlFor="active">Active, yes or no?</label>
                            </div>

                            <button className="btn btn-outline-dark w-25" type="submit">Go</button>
                        </form>

                    </div>
                    <div className="col-lg-4">
            
                        {errors.map((err) => {
                            return (
                                <div className="text-danger" key={err}>{err}</div>
                            );
                        })}
           
                    </div>
                </div>
            </div>
            <hr />
        </>
    );  
};

export default NewCategory;

I want the err.response.data.errors put into the setErrors([]) form state, so the form is rendered with the errors like how pre submitted errors are displayed on the client side. So, what do I need inside the catch block?

Les
  • 21
  • 1
  • 3
  • What is the issue? Not working? Any errors.. – Teddy Aug 23 '23 at 18:34
  • Just setErrors() again? But, that will only work if validation library errors format and your server response error formats are similar. Else, you could transform the server errors response into same format as that of validation library errors. Then you can just call setErrors(transform(data.errors)); – Teddy Aug 23 '23 at 18:36
  • It's how to transform the format from the server, to what react is expecting in the setErrors() state. I've tried setErrors(err.response.data.errors) but that doesn't work, yet the initial state is an array. – Les Aug 23 '23 at 19:06
  • You could just `console.log` both the formats, compare them, and think of a way to convert API error array to validation error array format. – Teddy Aug 24 '23 at 07:20
  • There are many ways, but array.map() is what I like ... refer: https://stackoverflow.com/a/3610487/1364747 – Teddy Aug 24 '23 at 07:20

0 Answers0