0

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>

    );
  }
}

1 Answer 1

4

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
}
Sign up to request clarification or add additional context in comments.

8 Comments

you don't have an example please?
but how i can include the posts details in the first function? sorry never i use the asyncstorage
It is not clear from the question where your array comes from so I have just placeholders in there
ok i resolve it, how i can get the bookmark list in FlatList component?
What's not complete? your question only asks how to save items to asyncStorage, @Tony 's answers shows how to save & retrieve them.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.