Replies: 2 comments
-
@Moshyfawn @bluebill1049 @jorisre @kotarella1110 |
Beta Was this translation helpful? Give feedback.
0 replies
-
I've got this hook for async error handling to ensure the error boundary I have catches the error. Inspired by this comment. import { useState } from 'react';
type ThrowError = (e: unknown) => void;
const useThrowError = (): ThrowError => {
const [, setState] = useState();
const throwError = (e: unknown): void =>
setState(() => {
throw e;
});
return throwError;
};
export default useThrowError; In the component with the form: const throwError = useThrowError();
const {
register
} = useForm<ItemForm>({
defaultValues: async () => {
try {
const item = await getItem(id);
return item;
} catch (error) {
throwError(error);
throw error; // rethrow, but only so TS does not complain about the return type
}
},
}); Edit: I should note that my call to |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Description
I'm utilizing React Hook Form in my project and seeking guidance on handling the catch block when setting default values asynchronously.
What I've Tried
I attempted to directly return the hardcoded default value in the catch block. However, this approach has limitations, especially in cases where the default value cannot be hardcoded and needs to be fetched from an API.
Additionally, I experimented with returning various default values, such as an empty object,
undefined
, or utilizing TypeScript'sPartial
type to signify incomplete default values until fetched from the server. However, these attempts resulted in TypeScript errors due to incomplete typings or mismatches when handling the asynchronous nature of fetching default values from an API endpoint.Code Example
hook
main component
Request
I'm looking for guidance or best practices specifically related to handling the catch block within React Hook Form's context when fetching default values asynchronously. Any insights or code examples demonstrating a robust error handling strategy in this scenario would be immensely valuable!
Beta Was this translation helpful? Give feedback.
All reactions