Just now I started using AsyncStorage. I tried storing input text value like this:
class Sample extends React.Component{ constructor(props){ super(props); this.state = { Name:' ', }; } componentDidMount() { AsyncStorage.getItem("Name").then((value) =>{ this.setState({"Name":value}) }).done(); handleChange(e){ AsyncStorage.setItem("Name", e.nativeEvent.text) this.setState({ email: e.nativeEvent.text }) } render(){ return( <View> <TextInput style={styles.textContainer} value={this.state.Name} placeholder="Name" onChange={this.handleChange.bind(this)}/> </View> ) }
For this it is working correctly, but i want to add a record into an array instead of changing the record every time. I want to push the record into an array and need to display the total array data in the view, (i.e) I need previously avilable data also.
Keep in mind that AsyncStorage can only store string values. In order to store object data you need to serialize it first. You can do this by using JSON. stringify() to store it and JSON.
To create and use an array in react native, just use square brackets [] it will create an array like the below example.
You can use AsyncStorage to store and load data to/from local storage. One thing to note is data MUST be a string, so anything like an object that is not a string needs to be stringified. You can use JSON. stringify(...) to do this.
On iOS, AsyncStorage is backed by native code that stores small values in a serialized dictionary and larger values in separate files. On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.
Use JSON.stringify and JSON.parse to store an array as a value via AsyncStorage
.
const stringifiedArray = JSON.stringify(somearray)
const restoredArray = JSON.parse(stringifiedArray)
AsyncStorage
return AsyncStorage.getItem('somekey') .then(req => JSON.parse(req)) .then(json => console.log(json)) .catch(error => console.log('error!')); const someArray = [1,2,3,4]; return AsyncStorage.setItem('somekey', JSON.stringify(someArray)) .then(json => console.log('success!')) .catch(error => console.log('error!'));
for setting
AsyncStorage.setItem('name', JSON.stringify(your array));
for getting
AsyncStorage.getItem('name', (error, result) => { this.setState({ name: JSON.parse(result) }, function () { });});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With