tcomb-form-native icon indicating copy to clipboard operation
tcomb-form-native copied to clipboard

help with default value

Open billtlee opened this issue 5 years ago • 5 comments

Version

Tell us which versions you are using:

  • tcomb-form-native v0.6.20
  • react-native v0.56

Hi,

This is probably a user error. I am trying out some of the examples from the doc. However, I am getting TypeError: Cannot read property 'value' of null. Can someone tell me what I am doing wrong? Thanks!

let Form = t.form.Form;

const PersonalData = t.struct({
  firstName: t.String,
  lastName: t.String,
  age: t.Number,
  mobile: t.String,
  email: t.String
});

const options = {};

export class User extends Component {

  getInitialState = () => {
    return {
      value: {
        firstName: 'John',
        lastName: 'Doe'
      }
    }
  };

  onChange = (value) => {
    this.setState({value});
  };

  onPress = () => {
    const value = this.refs.form.getValue();
    if (value) {
      console.log('value: ', value);
    }
  };

  render() {

    return (
      <View style={styles.container}>
        <Form 
          ref='form'
          type={PersonalData}
          value={this.state.value}
          onChange={this.onChange}
          options={options}
        />
        <Button onPress={this.onPress}>OK</Button>
      </View>
    );
  }
}

billtlee avatar Mar 11 '19 05:03 billtlee

If I add a constructor and remove getInitialState, it seems to work. Do I not need the getInitialState?

  constructor(props) {
    super(props);
    this.state={
      value: {
        firstName: 'John',
        lastName: 'Doe'
      }
    };
  };

billtlee avatar Mar 11 '19 05:03 billtlee

Another question about default value is, how do I set them using mobx or redux store?

billtlee avatar Mar 12 '19 04:03 billtlee

Hey @billtlee did you sort out an answer? I am just about to go down the same path and any help would be appreciated 😀

richlow avatar Mar 24 '19 06:03 richlow

@richlow Yes, I am currently using mobx. I'm pretty sure redux will work too. Here is what I did:

  constructor(props) {
    super(props);
    this.state={
      value: {
        field1: '',
        field2: ''
      }
    };
  };

  componentDidMount() {
    this.loadData();
  }

  loadData = async () => {
    try {
        await DataActions.loadData();
        this.setState({
          value: {
            field1: this.props.data.field1,
            field2: this.props.data.field2,
          }
        });
    } catch (e) {
        console.log('error: ', e);
    }
  }

I am getting values from an external source and loading them into the store in DataActions.loadData.

Hope this helps.

billtlee avatar Mar 24 '19 08:03 billtlee

Nice work! Thanks for that....

richlow avatar Mar 24 '19 08:03 richlow