Extending and displaying an array in asyncstorage in React-native

react native asyncstorage add to array
react native asyncstorage array
react native asyncstorage multiget example
react native asyncstorage best practices
async storage react native
update asyncstorage react native
react native asyncstorage return promise
react native asyncstorage callback example

I'm trying to add user-input to a specific array inside AsyncStorage. I am not sure if my current code is doing this. I can't display it via "alert()" and currently I am receiving this error : the bind value at index 1 is null"

async addAvailableActivity(){
  try {
    AsyncStorage.getItem('availableActivities')
    .then(activities => {this.availableActivities = JSON.parse(activities)})
  } catch (error) {
    alert('Couldnt load activities!')
  }

  let newActivity = this.state.newActivity
  this.availableActivities.push(newActivity)

  try {
    AsyncStorage.setItem('availableActivities', JSON.stringify(this.availableActivities))
  } catch (error) {
    alert('Couldnt add activity!')
  }

}

async displayAvailableActivities(){
  AsyncStorage.getItem(this.availableActivities).then(activities => {alert(activities)})    
}

There are a few problems with your code, first I would store availableActivities in your component state if you want to scope it like that. Second, when you call a function async you should be using await for your promises, third and most important AsyncStorage.getItem(this.availableActivities) this seems like a typo, but AsyncStorage key value pairs must be strings.

Here is an update to your code that I think will provide the functionality you're looking for:

addAvailableActivity = async () => {
  try {
    let activities = await AsyncStorage.getItem('availableActivities')
    let { newActivity } = this.state
    if (activities != null) {
      activities = JSON.parse(activities)
      activities.push(newActivity)
      await AsyncStorage.setItem( 'availableActivities', JSON.stringify(activities) )
    }
  } catch (error) {
    console.warn(error)
  }
}

displayAvailableActivities = () => {
  let activities = await AsyncStorage.getItem('availableActivities')
  console.warn(JSON.parse(activities))
}

note that I changed the function declarations, this isn't necessary but it prevents them from having to be bound in your constructor. async / await is an alternate syntax to .then which is much cleaner and easier to read. To check if AsyncStorage returned a value it's best to test it against null and finally, I fixed the typo in your last function. Let me know if you have any questions or if I missed the mark

Extending and displaying an array in asyncstorage in React-native, I'm trying to add user-input to a specific array inside AsyncStorage. I am not sure if my current code is doing this. I can't display it via "alert()" and currently I am  Introduction to React Native AsyncStorage. AsyncStorage in the react native is one kind of storage system where we can store the global variable for accessing them into our apps, it is always better to use the AsyncStorage instead of using the LocalStorage, basically AsyncStorage is asynchronous, persistent and unencrypted key-value storage system on the app, it would be good if we use the

This line

AsyncStorage.getItem(this.availableActivities).then(activities => {alert(activities)})

Should be

AsyncStorage.getItem('availableActivities').then(activities => {alert(activities)})

AsyncStorage · React Native, static multiSet(keyValuePairs, callback?) multiSet and multiMerge take arrays of key-value array pairs that match the output of multiGet, e.g. Returns a Promise  Array: Yes: Array of key for the items to get. callback?(errors: ?Array, result: ?Array<Array >) => void: No: Function that will be called with a key-value array of the results, plus an array of any key-specific errors found.

Looks like you are trying to get an item in incorrect way.

async displayAvailableActivities(){
 AsyncStorage.getItem(this.availableActivities).then(activities => {alert(activities)}) 
}

First param for getItem should be string:

async displayAvailableActivities(){
 AsyncStorage.getItem('availableActivities').then(activities => {alert(activities)})    
}

AsyncStorage getItem

How to use AsyncStorage to store array in React Native, How to use AsyncStorage to store array in React Native Or if you want to use this value as array to display something you have to convert it into json. //Class Home export default class Home extends Component  Inserting values in Array using Manually method. Showing Array Values in Text Component one by one like ListView. Adding onPress-onClick method on Array Item to get its value on click event. Contents in this project Create and Show Array Elements in Text using MAP in React Native : 1. Import StyleSheet, Text, View and Alert component in your

I think the problem is that you are using an AsyncStorage which cause Async in this way. I think in this way your code will work:

async addAvailableActivity(){
  try {
    AsyncStorage.getItem('availableActivities')
    .then(activities => {this.availableActivities = JSON.parse(activities)
    let newActivity = this.state.newActivity
    this.availableActivities.push(newActivity)
   })
  } catch (error) {
    alert('Couldnt load activities!')
  }

  try {
    AsyncStorage.setItem('availableActivities', JSON.stringify(this.availableActivities))
  } catch (error) {
    alert('Couldnt add activity!')
  }
} 

You also need to use it not exactly after this function. Use it some where else.

 async displayAvailableActivities(){
      AsyncStorage.getItem(this.availableActivities).then(activities => {alert(activities)})    
    }

Suggestion: You can also maintain all your states using Redux. You can also update and access your states from any screen that you want. Here is a good tutorial to help you start it: https://www.valentinog.com/blog/redux/

Array of objects inside Async Storage - React Native, Array of objects inside Async Storage - React Native - reactjs. and even display it in debugger console.log but when I want to map through array of data, App.js class App extends Component { constructor(props) { super(props) this.state  A React component for displaying different types of images, including network images, static resources, temporary local images, and images from local disk, such as the camera roll. This example shows fetching and displaying an image from local storage as well as one from network and even from data provided in the 'data:' uri scheme.

AsyncStorage - React Native By Example, stringify to turn the array into a string when sending it into storage and JSON.​parse to transform it back into an array when retrieving it. Play with AsyncStorage and  A React component for displaying different types of images, including network images, static resources, temporary local images, and images from local disk, such as the camera roll. This example shows fetching and displaying an image from local storage as well as one from network and even from data provided in the 'data:' uri scheme.

Chapter 9: Implementing cross-platform APIs, Although React Native offers other cross-platform APIs, you'll find these to be the Alert } from 'react-native' #1 let styles = {} export default class App extends and two buttons #4 If Show Message is pressed, updates the state to in AsyncStorage needs to be a string; JSON.stringify turns objects and arrays into strings. A React component for displaying text. Text supports nesting, styling, and touch handling. In the following example, the nested title and body text will inherit the fontFamily from styles.baseText, but the title provides its own additional styles. The title and body willstack on top of each other on account of the literal newlines:

Saving objects using AsyncStorage - Luis Bajaña, React Native has a fantastic API, and of course, it manages local storage pretty well, it does it through AsyncStorage with two simple methods setItem and getItem. So, I'll need to handle this as an array, since it is not supported by the API I'll  Both Android and iOS allow you to display formatted text by annotating ranges of a string with specific formatting like bold or colored text (NSAttributedString on iOS, SpannableString on Android). In practice, this is very tedious. For React Native, we decided to use web paradigm for this where you can nest text to achieve the same effect.

Comments
  • I've implemented it as this but am receiving only null values, when trying to display the values. This is my input: ' render(){ <Button onPress={this.addAvailableActivity} title="Add Activity"/>} constructor() { super() this.state = {} this.addAvailableActivity = this.addAvailableActivity.bind(this) } handleActivityInput(newText){ this.setState({ value: newText }) } '
  • @Kokonut: The reason is that your screen will render before your data retrieve. So you will see null. If I were in your shoes, I put this code in previous screen in the navigation point and obtain the data there. Then pass them to the current screen. In this way you won’t see null any more. Hope it helps you.
  • is there a way of centrally storing these values, so they become accesible across all screens even after closing the app?
  • @Kokonut: Yes, of course. You can use Redux. It will keep your states and update them from any screen that you want. Its only problem is that, it may be a little bit complex at the first glance. I hope I could help.
  • @Kokonut: I have updated my answer, you can check the link and if it was help full, please don't forget to vote it up.