tcomb-form-native
tcomb-form-native copied to clipboard
help with default value
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>
);
}
}
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'
}
};
};
Another question about default value is, how do I set them using mobx or redux store?
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 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.
Nice work! Thanks for that....