diff --git a/src/modules/register/UserRegister.tsx b/src/modules/register/UserRegister.tsx index ac11718..cfbb90f 100644 --- a/src/modules/register/UserRegister.tsx +++ b/src/modules/register/UserRegister.tsx @@ -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} /> - - + {registerError && isSubmitted && } - {isRegisteringUser && } diff --git a/src/modules/register/useUserRegister.tsx b/src/modules/register/useUserRegister.tsx index 834ebc6..9cbade9 100644 --- a/src/modules/register/useUserRegister.tsx +++ b/src/modules/register/useUserRegister.tsx @@ -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(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(); 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;