Closed skorphil closed 8 months ago
Error handling playground: https://jsfiddle.net/skorphil/cbxu10kp/40/
Not sure, but it looks like react-hook-form does not have a built-in mechanism for catching fetching errors. So error handling could be achieved via catching and setting state manually
defaultValues: async () => {
try {
await getLatestRecord();
} catch (error) {
console.log("defaultValues error:", error); // setState here
}
},
Created a new react Component, which takes error message as a prop. It displayed based on errorState in RecordForm
https://github.com/skorphil/nextjs-form/assets/6762009/952ec7ae-6c3c-499e-b940-d722e7d7651d
There is a bug - default values not receiving values after await
defaultValues: async () => {
try {
await getLatestRecord();
} catch (error) {
setErrorState(error.stack);
}
},
only this works:
defaultValues: async () => getLatestRecord();
so how to cath errors?
Probably can be done with useEffect:
useEffect(() => {
const fetchData = async () => {
try {
const data = await getLatestRecord();
setLatestRecord(data);
} catch (error) {
setErrorState(error.stack);
}
};
fetchData();
}, []);
But what the point in defaultValues compatible with promises?
Ah, that is
There is a bug - default values not receiving values after await
defaultValues: async () => { try { await getLatestRecord(); } catch (error) { setErrorState(error.stack); } },
only this works:
defaultValues: async () => getLatestRecord();
so how to cath errors?
ah, i just did not return the value - that was a problem
defaultValues: async () => {
try {
const initialValues = await getLatestRecord();
return initialValues; // here
} catch (error) {
setErrorState(error.stack);
}
},
When fetching initial data for the form fails, the error notification must be displayed