fix display of field errors from api

This commit is contained in:
leander committed 2024-07-26 03:09:41 +02:00
1 parent 702adabf84
commit 6668467594
2 files changed
+38 -8

No files matched your search

+14 -5
View File
@@ -13,8 +13,18 @@ import useUserRegister from './useUserRegister';
const { Toast } = Incubator;
const UserRegister = () => {
const { isRegisteringUser, onSubmit, isValid, control, errors, registerError, setFocus, toast, setToast } =
useUserRegister();
const {
isRegisteringUser,
onSubmit,
isValid,
isSubmitted,
control,
errors,
registerError,
setFocus,
toast,
setToast,
} = useUserRegister();
const isDisabled = isRegisteringUser || !isValid;
// TODO: validate on type
// TODO: highlight errorfields
@@ -72,10 +82,9 @@ const UserRegister = () => {
onSubmitEditing={onSubmit}
/>
<View style={styles.errorBox}>
<FormErrors errors={errors} />
<FormErrors errors={registerError} />
{registerError && isSubmitted && <FormErrors errors={registerError} />}
</View>
<Button fullWidth disabled={isDisabled} onPress={onSubmit} style={styles.registerButton}>
<Button fullWidth disabled={isDisabled} onPress={onSubmit} style={styles.registerButton} type="submit">
<Text>Registrer meg</Text>
</Button>
{isRegisteringUser && <ActivityIndicator color={theme.colors.neufOrange} />}
+24 -3
View File
@@ -19,7 +19,7 @@ const useUserRegister = () => {
const navigation = useNavigation();
const isAuthenticated = useAppSelector((store) => store.isAuthenticated);
const isRegisteringUser = useAppSelector((store) => store.isRegisteringUser);
const registerError = useAppSelector((store) => store.registerError) || {};
const registerError = useAppSelector((store) => store.registerError);
const [toast, setToast] = useState<ToastProps | null>(null);
const isAuthenticatedPrev = usePrevious(isAuthenticated);
@@ -27,11 +27,13 @@ const useUserRegister = () => {
const {
control,
handleSubmit,
formState: { errors, isValid },
formState: { errors, isValid, isSubmitted },
setFocus,
setError,
clearErrors,
} = useForm<UserRegisterFormValues>();
const onSubmit = handleSubmit((values) => {
clearErrors();
if (!isValid) {
setToast({
message: 'Noen av feltene er ikke fylt ut riktig',
@@ -56,6 +58,25 @@ const useUserRegister = () => {
}
}, [isAuthenticatedPrev, isAuthenticated, navigation]);
return { isRegisteringUser, onSubmit, isValid, registerError, control, errors, setFocus, toast, setToast };
useEffect(() => {
clearErrors();
if (!isSubmitted || !registerError) return;
Object.keys(registerError).forEach((key) => {
setError(key as keyof UserRegisterFormValues, { type: 'server', message: registerError[key].join('\n') });
});
}, [registerError]);
return {
isRegisteringUser,
onSubmit,
isValid,
isSubmitted,
registerError,
control,
errors,
setFocus,
toast,
setToast,
};
};
export default useUserRegister;