Search code examples
javascriptreactjsecmascript-6mobxmobx-react-form

Issue with mobx-react-forms


I am trying to get started with mobx-react-forms but am running into an error:

Unhandled Rejection (Error): Validation Error: Invalid Field Instance    
-> const form = new Form();

Here is my code:

import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Form as BaseForm } from 'mobx-react-form';
import validatorjs from 'validatorjs';

class Form extends BaseForm{
    plugins() {
        return { dvr: validatorjs };
    }

    setup(){
        return {
            fields: [{
                name: 'amount',
                label: 'Amount',
            }]
        }
    }

    hooks(){
        return {
            onSuccess(form) {
                alert('Form is valid! Send the request here.');
                // get field values
                console.log('Form Values!', form.values());
            },
            onError(form) {
                alert('Form has errors!');
                // get all form errors
                console.log('All form errors', form.errors());
            }
        };
    }
}

@observer
class PaymentForm extends Component {
    render() {    
        const form = new Form();

        return (
            <div>
                <h2>Payment Form</h2>

                <form onSubmit={form.onSubmit}>
                    <label>
                        {form.$('amount').label}
                        <input {...form.$('amount').bind()} />
                        <p>{form.$('amount').error}</p>
                    </label>
                </form>
            </div>
        )
    }
}

export default PaymentForm;

Solution

  • This turned out to be a versioning error I was running:

    "dependencies": {
      "axios": "^0.18.0",
      "custom-react-scripts": "^0.2.2",
      "expect": "^23.0.0-alpha.0",
      "mobx": "^4.1.0",
      "mobx-react": "^5.0.0",
      "mobx-react-form": "^1.32.3",
      "react": "^16.2.0",
      "react-dom": "^16.2.0",
      "react-redux": "^5.0.7",
      "react-router-dom": "^4.2.2",
      "validatorjs": "^3.14.2"
    },
    

    I downgraded to:

    "dependencies": {
      "axios": "^0.18.0",
      "custom-react-scripts": "^0.2.2",
      "expect": "^23.0.0-alpha.0",
      "mobx": "^3.3.1",
      "mobx-react": "^4.3.3",
      "mobx-react-form": "^1.32.3",
      "react": "^16.2.0",
      "react-dom": "^16.2.0",
      "react-redux": "^5.0.7",
      "react-router-dom": "^4.2.2",
      "validatorjs": "^3.13.5"
    }
    

    and things are now working.