简体   繁体   中英

How to save an array of Items in AsyncStorage React Native?

What i want to make is a bookmark list, but i don't know how i can save an array of items in AsyncStorage, my skills are basic on react.

I just need the function to save posts (post image, title and id) when i press the button "Save to bookmark".

export default class PostDetails extends Component {

constructor(props) {
   super(props);
   const {params} = props.navigation.state;
   this.state = {
     item: params.item
   };
}

render() {

   const {item} = this.state;  

   return (

   <Image source={{uri: item.post_image}}/>

   <Text> {item.post_id} </Text>
   <Text> {item.post_title} </Text>

   <Button>
      <Text> Save to Bookmark </Text>
   </Button>

    );
  }
}

I think you want to use JSON.stringify(arrayToSave) ; see the docs for JSON.stringify() . It will convert the array to a JSON string that can be saved to AsyncStorage and then can be retrieved at a later stage.

const saveBookmarks = async (bookmarksArray) => {
  try {
    const bookmarksString = JSON.stringify(bookmarksArray);
    await AsyncStorage.setItem('@MyStore:bookmarks',bookmarksString);
  } catch (error) {
    // Error saving data
  }
};

<Button onClick={() => saveBookmarks(yourArray)} />

To retrieve it you can use const theSavedArray = JSON.parse(stringFromAsyncStorage) ; the docs for JSON.parse()

try {
  const bookmarksString = await AsyncStorage.getItem('@MyStore:bookmarks');
  if (bookmarksString !== null){
    // We have data!!
    const bookmarksArray = JSON.parse(bookmarksString);
  }
} catch (error) {
  // Error retrieving data
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM