Trouble Implementing Client-Side Form Validation with Ruby on Rails API Backend
I'm attempting to set up Hey everyone, I'm running into an issue that's driving me crazy. I've looked through the documentation and I'm still confused about Currently developing a Rails API that needs to interact with a React frontend. The challenge arises when trying to implement client-side form validation with some intricate business logic. In my Rails controller, I have the following setup: ```ruby class UsersController < ApplicationController def create user = User.new(user_params) if user.valid? user.save render json: { user: user }, status: :created else render json: { errors: user.errors.full_messages }, status: :unprocessable_entity end end private def user_params params.require(:user).permit(:name, :email, :password) end end ``` On the front end, Iβm using React Hook Form for handling forms, and I've set up a basic validation schema with Yup. However, I want the validation to reflect server-side errors as well. Hereβs a snippet of how I set this up: ```javascript import { useForm } from 'react-hook-form'; import * as yup from 'yup'; import { yupResolver } from '@hookform/resolvers/yup'; const schema = yup.object().shape({ name: yup.string().required('Name is required'), email: yup.string().email().required('Email is required'), password: yup.string().min(6, 'Password must be at least 6 characters').required('Password is required'), }); const UserForm = () => { const { register, handleSubmit, setError } = useForm({ resolver: yupResolver(schema), }); const onSubmit = async (data) => { try { const response = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data), }); if (!response.ok) { const errorData = await response.json(); errorData.errors.forEach((error) => { setError(error.field, { type: 'manual', message: error.message }); }); } } catch (error) { console.error('Network error:', error); } }; return <form onSubmit={handleSubmit(onSubmit)}>...</form>; }; ``` The `setError` function works well for custom validation, but itβs unclear how to align the server response errors with the specific fields. My expectation is that when the server responds with validation errors, they should populate the respective fields in the form. Has anyone successfully achieved this level of integration? Any suggestions on how best to handle this would be greatly appreciated, especially regarding the structure of the error response from Rails and how to parse it in the frontend effectively. This is part of a larger web app I'm building. What am I doing wrong? I'm working on a service that needs to handle this. How would you solve this? This is for a mobile app running on Debian. Could this be a known issue?