diff --git a/src/App.js b/src/App.js index 3c96b66..cb0dfef 100644 --- a/src/App.js +++ b/src/App.js @@ -1,9 +1,13 @@ import React from 'react'; +import Comments from "./components/CommentsContainer/Comments"; + const App = () => { + console.log('render App'); + return ( <> - + ); }; diff --git a/src/components/CommentsContainer/CommentForm/CommentForm.js b/src/components/CommentsContainer/CommentForm/CommentForm.js new file mode 100644 index 0000000..866601f --- /dev/null +++ b/src/components/CommentsContainer/CommentForm/CommentForm.js @@ -0,0 +1,73 @@ +import React, {useContext, useRef, useState} from 'react'; + +import Input from "../../UI/Input/Input"; +import Button from "../../UI/Button/Button"; + +import {CommentsContext} from "../Comments"; +import TextArea from "../../UI/TextArea/TextArea"; + +const CommentForm = () => { + console.log('render CommentForm'); + + const [comments, setComments] = useContext(CommentsContext); + const formRef = { + name: useRef(''), + email: useRef(''), + body: useRef(''), + } + + const [saving, setSaving] = useState(false); + + const createComment = () => { + setSaving(true); + + fetch('https://jsonplaceholder.typicode.com/comments', { + method: 'POST', + body: JSON.stringify({ + postId: 1, + name: formRef.name.current.value, + email: formRef.email.current.value, + body: formRef.body.current.value + }), + headers: { + 'Content-type': 'application/json; charset=UTF-8', + }, + }) + .then((res) => res.json()) + .then((newComment) => { + // RESET FORM + formRef.name.current.value = ''; + formRef.email.current.value = ''; + formRef.body.current.value = ''; + + // NEW COMMENT + const newComments = [newComment, ...comments]; + setComments(newComments) + }) + .finally(() => { + setSaving(false); + }); + } + + const onSubmitHandler = (e) => { + e.preventDefault(); + + createComment() + } + + const onInputChange = (e, name) => { + formRef[name].current.value = e.target.value; + } + + return ( +
+ {onInputChange(e, 'name')}} placeholder={'Name'}/> + {onInputChange(e, 'email')}} placeholder={'Email'}/> + + + ); +}); + +export default TextArea; \ No newline at end of file diff --git a/src/index.js b/src/index.js index d563c0f..eaa6def 100644 --- a/src/index.js +++ b/src/index.js @@ -6,9 +6,9 @@ import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( - + // - + // ); // If you want to start measuring performance in your app, pass a function