V
V
Villas562020-01-07 11:14:13
JavaScript
Villas56, 2020-01-07 11:14:13

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);
    }
  }
}

And there is a form written in formik, where the method (action) is passed
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>
  );
};

In onSubmit, I pass the method from the store, but the form does not see that there are errors in this method (404, 500, server validation, etc., etc.) and onSubmit always outputs a try block.
How can I make it clear to the form that the method from the store did not pass and display errors? At the same time, I would very much like the method to remain in the store, if possible

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question