Next.js + React项目中处理PUT请求更新表单数据报错求助
Hey there! Let's figure out why your PUT request is failing and get your form update working smoothly. I'll walk through the key issues in your code and how to fix them step by step.
第一步:先抓准具体错误信息
Right now you only mentioned you're getting an error, but without details it's hard to pinpoint the root cause. First, update your error handling to log the full error details:
.catch((error) => { console.error("PUT 请求错误详情:", error.response?.data || error.message || error); // 如果你的 handleError 函数存在,也可以在这里补充它的逻辑 });
This will show you if it's a 400 (bad request data), 401 (authorization issue), 500 (server error), or another problem—critical info for troubleshooting.
第二步:修复表单初始化的问题
There are two key issues with how your form and user state are set up:
1. 修正用户状态的初始化
props.userProfile is a single user object, not an array, so you don't need to wrap it in brackets:
const [user, setUser] = useState(props.userProfile);
Then you can remove the map when rendering the form (since you're dealing with one user, not a list):
<form className="pt-5" onSubmit={form.onSubmit(handleSubmit)} > <TextInput label="Name" placeholder={user.data.name} {...form.getInputProps("name")} /> <TextInput label="Surname" placeholder={user.data.surname} {...form.getInputProps("surname")} /> <EmailField required name="email" label="Email" placeholder={user.data.email} {...form.getInputProps("email")} /> <button type="submit">Save</button> </form>
2. 正确设置react-hook-form的初始值
Your form starts with empty values, but it should pre-fill with the user's existing data. Update the useForm initialization:
const form = useForm({ initialValues: { name: user.data.name || "", surname: user.data.surname || "", email: user.data.email || "", }, });
If there's any chance the user data loads after the component mounts (unlikely here since you're using getServerSideProps, but just in case), add a useEffect to sync the form values:
useEffect(() => { if (user?.data) { form.reset({ name: user.data.name, surname: user.data.surname, email: user.data.email, }); } }, [user, form]);
第三步:修正异步请求的处理
Your handleSubmit calls an async function but doesn't handle it properly. Convert it to an async function for cleaner code and to ensure react-hook-form handles the submission correctly:
async function handleSubmit(values) { console.warn(values); try { const response = await protectedRequest("****(API endpoint)", "PUT", session, values); const updatedData = response.data.data; console.log(updatedData); // Update local state to show the latest user data immediately setUser({ data: updatedData }); } catch (error) { console.error("PUT 请求失败:", error.response?.data || error.message); // Add user-facing error feedback here (like a toast message) } }
第四步:检查请求格式与权限
- API Endpoint & Data Structure: Double-check that your PUT endpoint is correct (e.g., is it
/users/selflike your GET request?). Also, confirm if your backend expects the data in a specific format—some APIs require wrapping the user data in a parent key like{ user: values }:// Example if backend expects { user: { name, surname, email } } const response = await protectedRequest("/users/self", "PUT", session, { user: values }); - Authorization: Even though your GET request works, verify that your token has permission to update user data. You can log the token in the
handlePutfunction to ensure it's being passed correctly.
第五步:移除不必要的表单属性
Your form has method="post", which triggers the browser's default POST behavior. While react-hook-form should block this, removing the attribute avoids potential conflicts:
<form className="pt-5" onSubmit={form.onSubmit(handleSubmit)} >
Start with logging the full error details, then work through these fixes—this should resolve your PUT request issues.
内容的提问来源于stack exchange,提问作者Somdotta Sarkar

