diff --git a/package.json b/package.json index 490d2cc..ec796ee 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "private": true, "homepage": "https://boomcamp.github.io/react-3/", "dependencies": { + "axios": "^0.19.0", "faker": "^4.1.0", "json-server": "^0.15.0", "react": "^16.8.6", diff --git a/src/components/App.js b/src/components/App.js index b48f641..53eaf25 100644 --- a/src/components/App.js +++ b/src/components/App.js @@ -1,9 +1,13 @@ import React, { Component } from 'react'; +import axios from 'axios'; import './App.css'; import Header from './Header/Header'; import Compose from './Compose/Compose'; +import Post from './Post/Post'; + +axios.defaults.headers.common['Content-Type'] = 'application/json'; class App extends Component { constructor() { @@ -12,33 +16,82 @@ class App extends Component { this.state = { posts: [], }; + } - this.updatePost = this.updatePost.bind(this); - this.deletePost = this.deletePost.bind(this); - this.createPost = this.createPost.bind(this); + componentDidMount() { + axios + .get('http://localhost:9090/posts') + .then(response => this.setState({ posts: response.data })); } - componentDidMount() {} + updatePost = (id, text) => { + axios + .put(`http://localhost:9090/posts/${id}`, { text }) + .then(response => { + const updatedPost = response.data; + const updatedPosts = this.state.posts.map(post => { + if (post.id === updatedPost.id) { + return { post, ...updatedPost }; + } else { + return post; + } + }); + this.setState({ posts: updatedPosts }); + }); + } - updatePost() {} + deletePost = (id) => { + axios.delete(`http://localhost:9090/posts/${id}`).then(response => { + this.setState({ + posts: this.state.posts.filter(post => post.id !== id), + }); + }); + } - deletePost() {} + createPost = (text) => { + const date = new Date().toLocaleString('en-US', { + day: 'numeric', + month: 'short', + year: 'numeric', + }); - createPost() {} + axios + .post('http://localhost:9090/posts', { text, date }) + .then(response => + this.setState({ posts: [response.data, ...this.state.posts] }) + ); + } + + searchText = (text) =>{ + axios + .get(`http://localhost:9090/posts?q=${text}`) + .then(response => this.setState({ posts: [...response.data] })) + .catch(error => console.log(error)); + } render() { const { posts } = this.state; return (