Skip to content

Instantly share code, notes, and snippets.

@dcalixto
Created October 23, 2018 22:14
Show Gist options
  • Save dcalixto/5d9b3478d01b7acf38e92333a8a320bf to your computer and use it in GitHub Desktop.
Save dcalixto/5d9b3478d01b7acf38e92333a8a320bf to your computer and use it in GitHub Desktop.
posts
import React, { Component } from "react";
import axios from "axios";
import Comments from "../components/comments";
class PostShow extends Component {
constructor(props) {
super(props);
this.state = {
comments: [],
title: "",
error: null,
comment: "",
parent_id: ""
};
}
componentDidMount() {
this.fetchPost();
this.fetchComments();
}
fetchPost() {
const {
match: { params }
} = this.props;
return fetch(`/posts/${params.id}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => response.json())
.then(data => {
this.setState({
title: data.title
});
})
.catch(error => {
this.setState({ error });
return [];
});
}
fetchComments() {
const {
match: { params }
} = this.props;
return fetch(`/posts/${params.id}/comments`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => {
response.json();
})
.then(data => {
this.setState({
comments: data.comments
});
})
.catch(error => {
this.setState({ error });
return [];
});
}
submitComment() {
const {
match: { params }
} = this.props;
fetch(`/posts/${params.id}/comments`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
comment: {
commentable_id: params.id,
comment: this.state.comment,
commentable_type: "Post",
parent_id: "",
post_id: params.id
}
})
})
.then(response => {
if (response.status >= 200 && response.status < 300) {
return response.text();
} else {
return response.json();
//let errors = response.json();
//throw errors;
}
})
.then(response => {
this.setState({
errors: response
});
})
.catch(err => {});
}
postComment(e) {
this.setState({ comment: e.target.value });
}
render() {
const { comments } = this.state;
return (
<div>
{this.state.title}
<form>
<textarea
name="comment"
rows={this.props.textareaRows}
placeholder="post a comment"
value={this.state.comment}
onChange={this.postComment.bind(this)}
/>
<input
type="hidden"
name="parent_id"
value={this.state.parent_id}
/>
<button
onClick={this.submitComment.bind(this)}
type="submit"
>
Submit
</button>
</form>
<div>
<h2>Comments</h2>
///
<Comments comments={comments} />
</div>
</div>
);
}
}
export default PostShow;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment