From 5060bed65bc6fdcbacf354f8d18d093f1aa507d3 Mon Sep 17 00:00:00 2001 From: SandraBergstrom Date: Fri, 23 Jun 2023 08:15:22 +0000 Subject: [PATCH] #14 Add function to create post, alets, redirect to post --- src/pages/posts/PostCreateForm.js | 61 +++++++++++++++++++++++++++++-- 1 file changed, 58 insertions(+), 3 deletions(-) diff --git a/src/pages/posts/PostCreateForm.js b/src/pages/posts/PostCreateForm.js index ac84fe3..c1cdd2f 100644 --- a/src/pages/posts/PostCreateForm.js +++ b/src/pages/posts/PostCreateForm.js @@ -1,10 +1,11 @@ -import React, { useState } from "react"; +import React, { useRef, useState } from "react"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import Row from "react-bootstrap/Row"; import Col from "react-bootstrap/Col"; import Container from "react-bootstrap/Container"; +import Alert from "react-bootstrap/Alert"; import Upload from "../../assets/upload.png"; import Asset from "../../components/Asset"; @@ -12,7 +13,11 @@ import Asset from "../../components/Asset"; import styles from "../../styles/PostCreateEditForm.module.css"; import appStyles from "../../App.module.css"; import btnStyles from "../../styles/Button.module.css"; +import alertStyles from "../../styles/AlertMessages.module.css"; + import { Image } from "react-bootstrap"; +import { useHistory } from "react-router-dom"; +import { axiosReq } from "../../api/axiosDefaults"; function PostCreateForm() { const [errors, setErrors] = useState({}); @@ -24,6 +29,9 @@ function PostCreateForm() { }); const { title, content, image } = postData; + const imageInput = useRef(null); + const history = useHistory(); + const handleChange = (event) => { setPostData({ ...postData, @@ -41,6 +49,25 @@ function PostCreateForm() { } }; + const handleSubmit = async (event) => { + event.preventDefault(); + const formData = new FormData(); + + formData.append("title", title); + formData.append("content", content); + formData.append("image", imageInput.current.files[0]); + + try { + const { data } = await axiosReq.post("/posts/", formData); + history.push(`/posts/${data.id}`); + } catch (err) { + console.log(err); + if (err.response?.status !== 401) { + setErrors(err.response?.data); + } + } + }; + const textFields = (
@@ -52,6 +79,15 @@ function PostCreateForm() { onChange={handleChange} /> + {errors.title?.map((message, idx) => ( + + {message} + + ))} A few words about this moment... + {errors.content?.map((message, idx) => ( + + {message} + + ))} @@ -76,7 +121,7 @@ function PostCreateForm() { ); return ( -
+ + {errors.image?.map((message, idx) => ( + + {message} + + ))}
{textFields}