already_bookmark in the SinglePost.js file in order to handle the showing of bookmark enabled or disabled icon. For that, we need to use the code from the following code snippet: constructor(props) {
super(props);
this.state = {
isloading: true,
post: [],
already_bookmark: false,
};
}<List.Item
title={`Published on ${moment(
post[0].date,
'YYYYMMDD',
).fromNow()}`}
right={props => {
if (this.state.already_bookmark == true) {
return (
<TouchableOpacity
onPress={() => this.removeBookMark(post[0].id)}>
<FontAwesome name="bookmark" size={30} />
</TouchableOpacity>
);
} else {
return (
<TouchableOpacity
onPress={() => this.saveBookMark(post[0].id)}>
<FontAwesome name="bookmark-o" size={30} />
</TouchableOpacity>
);
}
}}
/>already_bookmark state. The template has the TouchableOpacity component that wraps the FontAwesome component. In the onPress events we have called the removeBookMark and saveBookMark function. These functions are use to bookmark the article or remove the bookmark from the article.@react-native-community/async-storage package. For that, we need to use install the package first. In order to install the package we need to run the command from the following code snippet:
yarn add @react-native-community/async-storagepackage documentation.
import AsyncStorage from '@react-native-community/async-storage';Save Bookmark
saveBookMark = async post_id => {
this.setState({already_bookmark: true});
};already_bookmark state variable to true.AsyncStorage. For that, we need to use the code from the following code snippet: saveBookMark = async post_id => {
this.setState({already_bookmark: true});
let bookmark = [];
bookmark.push(post_id);
AsyncStorage.setItem('bookmark', JSON.stringify(bookmark));
};AsyncStorage to save the bookmark. We have saved the bookmark array as a JSON value. saveBookMark = async post_id => {
this.setState({already_bookmark: true});
await AsyncStorage.getItem('bookmark').then(token => {
const res = JSON.parse(token);
if (res !== null) {
let data = res.find(value => value === post_id);
if (data == null) {
res.push(post_id);
AsyncStorage.setItem('bookmark', JSON.stringify(res));
}
} else {
let bookmark = [];
bookmark.push(post_id);
AsyncStorage.setItem('bookmark', JSON.stringify(bookmark));
}
});
};Summary
AsyncStorage module. Using it, we implemented the function to save method