Answer the question
In order to leave comments, you need to log in
How to correctly pass a method from the store to formik in order to handle server errors?
Hello!
I have a post method in the signUpUser store.
import {
configure,
observable,
action,
runInAction,
} from 'mobx';
import axios from 'axios';
import get from 'lodash/get';
configure({ enforceActions: 'observed' });
type codeType = number | null;
export class UserStore {
@observable status: string = 'pending';
@observable errorMessage: {} = {};
@observable code: codeType = null;
@action
signUpUser = async (signValue: {}) => {
this.status = 'progress';
this.errorMessage = {};
this.code = null;
try {
await axios.post('/signup', signValue);
runInAction(() => {
this.status = 'succes';
});
} catch (error) {
runInAction(() => {
this.status = 'pressF';
this.errorMessage = get(error, 'response.data.message.errors', null);
this.code = get(error, 'response.status', null);
});
}
if (this.status === 'pressF' || 'succes') {
setTimeout(() => {
runInAction(() => {
this.status = 'pending';
});
}, 2500);
}
}
}
const SignUp = ({ userStore }: any) => {
const [, setStatus] = useState(userStore.status);
useEffect(() => {
if (!userStore.status) {
setStatus(userStore.status);
}
}, [userStore.status]);
const onSubmit = async (values: {}, { resetForm, setSubmitting }: FormikValues) => {
try {
if (userStore.code === 404) {
setSubmitting(false);
console.log('kek');
}
await userStore.signUpUser(values);
resetForm();
} catch (error) {
console.log(error, 'error');
}
};
return (
<Formik
initialValues={defaultValues}
validate={onValidate}
onSubmit={onSubmit}
validationSchema={SignUpSchema}
enableReinitialize
>
{props => (
<Entry>
<SubmitWrap>
<Submit
status={userStore.status}
disabled={props.isSubmitting}
type='submit'
/>
</SubmitWrap>
</Entry>
)}
</Formik>
);
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question