question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How can I make an API call onSubmit and handle the errors?

See original GitHub issue

I’m looking at the docs it’s not clear to me where to make an API call when submitting the form. I also need to find out how to show server errors for each field.

I tried adding an onSubmit function to the class and it gets called but the hooks do not work.

Store

import MobxReactForm from 'mobx-react-form';
import validatorjs from 'validatorjs';

const plugins = { dvr: validatorjs };

const fields = [
  {
    name: 'email',
    label: 'Email',
    placeholder: 'Insert Email',
    rules: 'required|email|string|between:5,25',
    value: 's.jobs@apple.com'
  },
  {
    name: 'password',
    label: 'Password',
    placeholder: 'Insert Password',
    rules: 'required|string|between:5,25',
  }
];

const hooks = {
  onSuccess(form) {
  //  I want to handle success here
    console.log('Form Values!', form.values());
  },
  onError(form) {
    //  I want to handle errors here
    console.log('All form errors', form.errors());
  }
};

class LoginForm extends MobxReactForm {
  static storeName = 'loginForm';

  constructor() {
    super({ fields }, { plugins, hooks });
  }
}

export default LoginForm;

const storeName = LoginForm.storeName;

export {
  storeName,
}

Component

import React, { Component } from 'react';
import Header from '../../components/Header';
import { Grid, Row } from 'react-bootstrap';
import { observer, inject } from 'mobx-react';
import PropTypes from 'prop-types';

@inject('loginForm')
@observer
class Test extends Component {
  render() {
    const form = this.props.loginForm;
    console.log(form);
    const email = form.$('email');
    const password = form.$('password');
    return (
      <form onSubmit={form.onSubmit}>

        <div>
          <input
            type="text"
            {...email.bind()}
          />
          <p>{email.error}</p>
        </div>

        <div>
          <input
            type="text"
            {...password.bind()}
          />
          <p>{password.error}</p>
        </div>

        <button>Submit</button>

      </form>
    );
  }
}

Test.propTypes = {};

Test.defaultProps = {};

export default Test;

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
elliotykimcommented, Jan 7, 2019

On a side note, focus() doesn’t appear to work consistently for fields. I tried forcing focus on the field before/after invalidate() so the async validation wouldn’t clear my error but had mixed results.

In the end, I used these options with success:

const options = {
  validateOnBlur: false,
  validateOnChange: true
}

@webdeveloperpr

1reaction
betancourtlcommented, Apr 19, 2018

Ok I ended up setting the errors using a timeout to bypass the issue. This feels so hacky.

import MobxReactForm from 'mobx-react-form';
import validatorjs from 'validatorjs';
import { authenticate } from "../api/auth";

const plugins = { dvr: validatorjs };

const fields = [
  {
    name: 'email',
    label: 'Email',
    placeholder: 'Insert Email',
    rules: 'required|string|between:5,40|email',
    value: 'webdeveloperpr@gmail.com'
  },
  {
    name: 'password',
    label: 'Password',
    placeholder: 'Insert Password',
    rules: 'required|string|between:5,25',
    value: '123qweQWE',
    type: 'text'
  }
];


const hooks = {
  onSuccess(form) {
    //  I want to handle success here
    authenticate({
      email: form.$('email').value,
      password: form.$('password').value,
    })
      .then(({ user, token }) => {
        this.rootStore.session.startSession(user, token);
      })
      .catch(err => {
      
      // Prevents the text input's onBlur event from removing the async errors. The unblur event triggers a validation check.
        setTimeout(() => {
          if (err.email) {
            form.validate('email')
              .then(({ isValid }) => {
                console.log('isValid', isValid);
                form.$('email').invalidate(err.email);
              });
          }

          if (err.password) {
            form.validate('password')
              .then(({ isValid }) => {
                form.$('password').invalidate(err.password);
              });
          }

        }, 250);
      });
  },
  onError(form) {
    //  I want to handle errors here
    console.log('All form errors', form.errors());
  }
};

class LoginForm extends MobxReactForm {
  static storeName = 'loginForm';

  constructor() {
    super({ fields }, { plugins, hooks });
  }
}

export default LoginForm;

const storeName = LoginForm.storeName;

export {
  storeName,
}

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to make an API call that requires info from another API ...
In my opinion the best way to handle the second API call is by conditionally rendering a second component which initiates loading the...
Read more >
useForm - handleSubmit - React Hook Form
Performant, flexible and extensible forms with easy-to-use validation.
Read more >
React Hook Form - Display custom error message returned ...
This is a quick example of how to display a custom error message on a React Hook Form that is returned from an...
Read more >
Submit Validation Example - Redux Form
The recommended way to do server-side validation with redux-form is to return a rejected promise from the onSubmit function. There are two ways...
Read more >
Final Form Docs
onSubmit is a function that will be called with the values of your form when the user submits the form and all validation...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found