foxhound87 / mobx-react-form

Reactive MobX Form State Management
https://foxhound87.github.io/mobx-react-form
MIT License
1.09k stars 129 forks source link

[Help Needed] How can I plug MobX store with MobX-React-Form #392

Closed jkeruzec closed 6 years ago

jkeruzec commented 6 years ago

Hello,

I'm trying to use mobx-rest to manage my data store from my rest API. I can't figure how to plug those observable store with async fetch to specific form values.

If anyone can help me, it would be much appreciated.

Thanks !

electricBonfire commented 6 years ago

+1

It would be nice to see some use case examples!

jkeruzec commented 6 years ago

I made it work : Please find an example :

    import { Form } from 'mobx-react-form'
    import validatorjs from 'validatorjs'
    import testsCollection from '../../store/collection/TestsCollection'
    import TestModel from '../../store/model/TestModel'
    import {action} from 'mobx'

    export default class HomePageFormDef extends Form {

    testModel;

    /*
    Below we are returning a `plugins` object using the `validatorjs` package
    to enable `DVR` functionalities (Declarative Validation Rules).
     */
    plugins() {
        return { dvr: validatorjs };
    }

    /**
     * Setup form property
     */
    setup() {

        this.createNewModel();
        this.printEmail(this.testModel);
        const fields = {
                email: {
                    label: 'Email',
                    placeholder: 'Insert Email',
                    rules: 'required|email|string|between:5,25',
                default: 'empty...'
                }
        };

        return ({fields});
    }

    @action
    createNewModel() {
        this.testModel = new TestModel({id: 1});
    }

    async printEmail(testModel) {
        const promise = testModel.fetch();
        console.log(testModel.isRequest('fetching'));
        await promise;
        console.log(testModel.get('email'));
    }

    /**
     * Hook serves like a controller for Javascript
     */
    hooks() {
        return {

            onInit(form) {
                testsCollection.fetch().then(
                        val => {
                            form.update(val[0]);
                        }, val  => {
                            console.debug("error");
                        }
                );
                console.log(form.values());
            },

            onSuccess(form) {
                // get field values
                console.log('Form Values!', form.values());
            },
            onError(form) {
                // get all form errors
                console.log('All form errors', form.errors());
            }
        };
    }

};