Arpith Siromoney 💬

Liking a Post in Constellational

The app I’m building to share notes, Constellational, lets you keep track of what you’ve read recently. I’ve now added a way to keep track of your favourite posts by adding a star to them. This is how I did it in React Native.

Adding a Star to a Post

So you’ve read a post you liked, and want to add it to your favourites. When you tap ‘Star’ a new post is created containing the username and url of this post:

if (selectedOption === 'Star') {
 let post = {
   type: 'star',
   data: {
     url: this.props.post.url,
     username: this.props.post.username
   }
 };
 PostActions.create(post);
}

This makes removing the post from your list of favourites easy, it’s just a delete:

if (selectedOption === 'Remove Star') {
 PostActions.del(this.props.post);
}

Displaying a Starred Post

When it comes to displaying a post that you’ve added a star to, the post details are first fetched with the username/url that you stored earlier, before rendering as usual:

render() {
 let noteText = '';
 let post = this.props.post;

 if (post.isDraft) noteText = 'Draft';
 if (post.hasUnpublishedEdits) noteText = 'Editing';
 if (post.type === 'star') {
   noteText = 'Starred';
   post = PostStore.getPost(post.data.username, post.data.url);
 }
  return (
   <TouchableOpacity onPress={this.showOptions}>
     <View style={styles.post}>
       <Text style={styles.note}>{noteText}</Text>
       <Text style={styles.text}>{post.data}</Text>
       <Text style={styles.time}>
         {moment(post.updated).format('LLLL')}
       </Text>
     </View>
   </TouchableOpacity>
 );
 }
}

Displaying the option to Star / Remove Star

For now I’m using an action sheet that opens up when you tap the post to display actions you can take. Depending on whether the post is created by the user (or is someone else’s post that is being viewed) a different set of options are displayed:

showOptions() {
 let params = {};
 
 if (this.props.post.username === SettingStore.getUsername()) {
   params = {
     options: ['Share', 'Edit', 'Delete', 'Cancel'],
     destructiveButtonIndex: 2,
     cancelButtonIndex: 3
   };
 } else {
   let options = ['Star', 'Share', 'Cancel'];
   if (this.props.post.type === 'star') options[0] = 'Remove Star';
   params = {
     options: options,
     cancelButtonIndex: 2
   }
 }
  let handleOptions = (buttonIndex) => {   
   this.handleOptions(params.options[buttonIndex]);
 };
  ActionSheetIOS.showActionSheetWithOptions(params, handleOptions);
}

That’s about it! This fixes #80.

Still to come: displaying the number of times your post has been liked.

Sounds interesting? Sign up here!