I am making an app which contains a notes field which needs to keep its input after the screen changes, but it always resets after you leave the page. Here is my constructor for the state:
this.state = {text: ""};
And my textinput declaration:
<TextInput
style={{
height: 200,
width: 250,
fontSize: 15,
backgroundColor: 'white',
}}
editable = {true}
multiline = {true}
numberofLines = {4}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
I've been trying to find a way to set the state to a variable that doesn't get reinitialized on opening the page up but have no luck so far. Any advice would be appreciated!
Use AsyncStorage
to persist the input value. For eg:
<TextInput
style={{
height: 200,
width: 250,
fontSize: 15,
backgroundColor: 'white',
}}
editable = {true}
multiline = {true}
numberofLines = {4}
onChangeText={(text) => {
this.setState({text});
AsyncStorage.setItem('inputKey', text); // Note: persist input
}}
value={this.state.text}
/>
Then inside componentDidMount you can check for the value and update state accordingly to reinitialise with old value.
componentDidMount() {
AsyncStorage.getItem('inputKey').then((value) => {
if (value !== null){
// saved input is available
this.setState({ text: value }); // Note: update state with last entered value
}
}).done();
}