Search code examples
javascriptmobxmobx-reactmobx-react-form

Trying to use mobX to replace setState


Trying to replace setState in react. Having issues changing value of this.info using observable in mobX. When I console.log(e.target.name, e.target.value) the value only returns one letter.

//Login
import * as React from 'react';
import { extendObservable } from 'mobx';
import { observer }  from 'mobx-react';

constructor(props) {
        super(props);

        extendObservable(this, {
            info: {
                username: '',
                password: ';
            }
        })
    }

onChange = (name, value) => {
    this.info[name] = value
}

render(){
    <LoginForm info={this.info} onChange={this.onChange}/>
}
//LoginForm
import * as React from 'react';
import {Form} from "semantic-ui-react";

const onChange = (props) => (e) => {
    props.onChange(e.target.name, e.target.value)
    console.log(e.target.name, e.target.value)
};

const LoginForm = (props) => {
    return (
                    <Form.Input fluid label='username' placeholder='username' name="username"
                                value={props.info.username|| ''}
                                onChange={onChange(props)} type="text" />
                    <Form.Input fluid label='password' placeholder='password' name="password"
                                value={props.info.passoword || ''}
                                onChange={onChange(props)} type="text"/>
    )
}



Solution

  • what about try this? change info object not value in object

    import { action, extendObservable } from "mobx";
    onChange = action((name, value) => {
      this.info = { ...this.info , [name]: value };
    });