What I have is a feed where you can post entries. These entries can then be liked by any user. The problem is that after you like an entry and continue with writing your own entry right after(thus pushing the new entry to the top of the feed) the state of all the like buttons that you have clicked will be undone visually and in order to see the correct data being displayed a manual refresh is required.
This problem is very peculiar and I have unfortunately not found anything that could relate to this.
Here is my code for the Like component(like.es6.jsx):
class Like extends React.Component {
constructor(props){
super(props);
this.state={
like: this.props.entry.liked,
likes: this.props.entry.likes_count
}
this.post = this.post.bind(this);
this.delete = this.delete.bind(this);
}
post () {
if(!(this.state.like)){
$.ajax({
method: "POST",
url: "/api/v1/likes",
data: {
log_entry_id: this.props.entry.id
},
})
.then( (response) => {
this.setState({like: true})
let likes = this.state.likes;
likes++;
this.setState({likes: likes})
});
}
}
delete(){
if(this.state.like){
$.ajax({
method: "DELETE",
url: "/api/v1/likes/" + this.props.entry.id
})
.then( (response) => {
this.setState({like: false})
let likes = this.state.likes;
likes--;
this.setState({likes: likes})
});
}
}
render () {
let show_likes = "";
if(this.state.like) {
show_likes = (this.state.likes > 1) ? ("You and " + (this.state.likes - 1) + ((this.state.likes == 2) ? (" other person") : (" others" )) + (" like this.")) : ("You like this.");
}else if(this.state.likes > 0){
show_likes = (this.state.likes == 1) ? (this.state.likes + " person likes this.") : (this.state.likes + " people like this.");
}
let like_button = this.state.like ?
<a onClick={this.delete} className=" pull-right"><i className="fa fa-thumbs-o-down"></i> Dislike</a> :
<a onClick={this.post} className=" pull-right"><i className="fa fa-thumbs-o-up"></i> Like</a>
return (
<div>
<span>
{show_likes}
</span>
{like_button}
</div>
);
}
}
In the parent component 'log_entry.es6.jsx' I've added my like component in the following way:
<Like entry={entry} key={entry.id} />
If there's any more information I can supply with I'll happily do it upon request. Thank you for your time reviewing my problem!