fix double posts on double click

This commit is contained in:
Niklas 2025-07-04 11:25:18 +02:00 committed by MisbehavedNinjaRadiator
parent 0a3a406180
commit 2641e5cf19

View file

@ -1,6 +1,13 @@
import { useState, useEffect, useRef } from "react"; import { useState, useEffect, useRef } from "react";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { Box, Card, CardMedia, CardActionArea, IconButton, Typography } from "@mui/material"; import {
Box,
Card,
CardMedia,
CardActionArea,
IconButton,
Typography,
} from "@mui/material";
import Chip from "@mui/material/Chip"; import Chip from "@mui/material/Chip";
import Autocomplete from "@mui/material/Autocomplete"; import Autocomplete from "@mui/material/Autocomplete";
import TextField from "@mui/material/TextField"; import TextField from "@mui/material/TextField";
@ -14,17 +21,18 @@ import "./postCreation.css";
const theme = createTheme({ const theme = createTheme({
palette: { palette: {
primary: { primary: {
main:'#e79a0e;' main: "#e79a0e;",
} },
} },
}); });
function PostCreation(){ function PostCreation() {
const {user} = useAuth(); const { user } = useAuth();
interface ImageItem { interface ImageItem {
src: string; src: string;
title: string; title: string;
} }
const [isSend, setIsSend] = useState<boolean>(false);
const [options, setOptions] = useState<string[]>([]); const [options, setOptions] = useState<string[]>([]);
const [tags, setTags] = useState<string[]>([]); const [tags, setTags] = useState<string[]>([]);
const [description, setDescription] = useState<string>(""); const [description, setDescription] = useState<string>("");
@ -33,7 +41,7 @@ function PostCreation(){
const [data, setData] = useState<ImageItem[]>([]); const [data, setData] = useState<ImageItem[]>([]);
const navigate = useNavigate(); const navigate = useNavigate();
const [fileList,setFileList] = useState<File[]>([]); const [fileList, setFileList] = useState<File[]>([]);
const inputFile = useRef<HTMLInputElement | null>(null); const inputFile = useRef<HTMLInputElement | null>(null);
useEffect(() => { useEffect(() => {
@ -46,7 +54,9 @@ function PostCreation(){
console.log(err); console.log(err);
} }
})(); })();
return () => { cancelled = true; }; return () => {
cancelled = true;
};
}, []); }, []);
const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { const handleChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
@ -69,31 +79,37 @@ function PostCreation(){
const newItems: ImageItem[] = Array.from(files).map((file) => ({ const newItems: ImageItem[] = Array.from(files).map((file) => ({
src: URL.createObjectURL(file), src: URL.createObjectURL(file),
title: file.name, title: file.name,
} }));
));
const lastImageUrl = newItems[newItems.length - 1].src; const lastImageUrl = newItems[newItems.length - 1].src;
setData((prev) => [...prev, ...newItems]); setData((prev) => [...prev, ...newItems]);
setSelectedImage(lastImageUrl); setSelectedImage(lastImageUrl);
setFileList(prev => [...prev, ...fileArr]); setFileList((prev) => [...prev, ...fileArr]);
} }
}; };
const onEmptyImgClick = () =>{ const onEmptyImgClick = () => {
if(inputFile.current){ if (inputFile.current) {
inputFile.current?.click(); inputFile.current?.click();
} }
} };
const handleDelete = (idx: number) =>{ const handleDelete = (idx: number) => {
setData((prev) => prev.filter((_, i) => i !== idx)); setData((prev) => prev.filter((_, i) => i !== idx));
if((idx-1)<0){ if (idx - 1 < 0) {
if(data.length == 1){setSelectedImage("");} if (data.length == 1) {
else{setSelectedImage(data[idx+1].src);} setSelectedImage("");
} else {
setSelectedImage(data[idx + 1].src);
} }
else {setSelectedImage(data[idx-1].src);} } else {
setSelectedImage(data[idx - 1].src);
} }
};
const onSubmit = async (event: React.FormEvent) => {
if (!isSend) {
setIsSend(true);
const onSubmit = async(event: React.FormEvent) =>{
event.preventDefault(); event.preventDefault();
if (!fileList) { if (!fileList) {
return; return;
@ -102,26 +118,27 @@ function PostCreation(){
files.forEach((file, i) => { files.forEach((file, i) => {
fData.append(`images`, file, file.name); fData.append(`images`, file, file.name);
}); });
fData.append('status','PUBLIC'); fData.append("status", "PUBLIC");
fData.append('description', description); fData.append("description", description);
tags.forEach((tag) => { tags.forEach((tag) => {
fData.append("tags" ,tag); fData.append("tags", tag);
}) });
try { try {
await api.post("/posts/upload", fData) await api.post("/posts/upload", fData);
navigate(`/profile/${user?.username}`) navigate(`/profile/${user?.username}`);
} catch (error:any) { } catch (error: any) {
console.log(error); console.log(error);
} }
}
}; };
const onCancel= () => { const onCancel = () => {
navigate(`/profile/${user?.username}`) navigate(`/profile/${user?.username}`);
}; };
const files = fileList ? [...fileList] : []; const files = fileList ? [...fileList] : [];
return( return (
<ThemeProvider theme={theme}> <ThemeProvider theme={theme}>
<div className="create-display"> <div className="create-display">
<div className="create-part"> <div className="create-part">
@ -129,30 +146,44 @@ function PostCreation(){
<h1>Create Post</h1> <h1>Create Post</h1>
<div className="create-layout"> <div className="create-layout">
<div className="create-preview"> <div className="create-preview">
{selectedImage? {selectedImage ? (
<img src={selectedImage} className="create-post-image" alt="Add an Image"></img>: <img
<label className="create-post-img-layer" onClick={onEmptyImgClick}> src={selectedImage}
className="create-post-image"
alt="Add an Image"
></img>
) : (
<label
className="create-post-img-layer"
onClick={onEmptyImgClick}
>
<strong>Add Picture</strong> <strong>Add Picture</strong>
</label>} </label>
)}
</div> </div>
<div className="create-post-desc"> <div className="create-post-desc">
<h2>Description*</h2> <h2>Description*</h2>
<textarea className="create-post-description" value={description} onChange={handleChange} required></textarea> <textarea
className="create-post-description"
value={description}
onChange={handleChange}
required
></textarea>
</div> </div>
<Box <Box
className="strip" className="strip"
sx={{ sx={{
display: 'flex', display: "flex",
gap: 1, gap: 1,
py: 1, py: 1,
overflowX: 'auto', overflowX: "auto",
overflowY: 'hidden', overflowY: "hidden",
width: '100%', width: "100%",
maxWidth: { xs: '90vw', sm: '600px' }, maxWidth: { xs: "90vw", sm: "600px" },
mx: 'auto', mx: "auto",
scrollSnapType: 'x mandatory', scrollSnapType: "x mandatory",
'& > *': { scrollSnapAlign: 'center' }, "& > *": { scrollSnapAlign: "center" },
'::-webkit-scrollbar': { display: 'none' }, "::-webkit-scrollbar": { display: "none" },
}} }}
> >
{/* Upload card */} {/* Upload card */}
@ -163,21 +194,27 @@ function PostCreation(){
minWidth: 60, minWidth: 60,
width: 60, width: 60,
height: 60, height: 60,
display: 'flex', display: "flex",
alignItems: 'center', alignItems: "center",
justifyContent: 'center', justifyContent: "center",
flexShrink: 0, flexShrink: 0,
}} }}
> >
<label style={{ cursor: 'pointer', width: '100%', height: '100%' }}> <label
<img src="/assets/icons/add-plus.svg" alt="Upload" style={{ width: '100%', height: '100%' }}/> style={{ cursor: "pointer", width: "100%", height: "100%" }}
>
<img
src="/assets/icons/add-plus.svg"
alt="Upload"
style={{ width: "100%", height: "100%" }}
/>
<input <input
id="create-file-upload" id="create-file-upload"
type="file" type="file"
accept="image/*" accept="image/*"
multiple multiple
onChange={handleImageUpload} onChange={handleImageUpload}
style={{ display: 'none' }} style={{ display: "none" }}
ref={inputFile} ref={inputFile}
required required
/> />
@ -190,7 +227,7 @@ function PostCreation(){
key={`${item.title}-${idx}`} key={`${item.title}-${idx}`}
variant="outlined" variant="outlined"
sx={{ sx={{
position: 'relative', position: "relative",
minWidth: 60, minWidth: 60,
width: 60, width: 60,
height: 60, height: 60,
@ -206,22 +243,26 @@ function PostCreation(){
handleDelete(idx); handleDelete(idx);
}} }}
sx={{ sx={{
position: 'absolute', position: "absolute",
top: 2, top: 2,
right: 2, right: 2,
backgroundColor: 'background.paper', backgroundColor: "background.paper",
zIndex: 1, zIndex: 1,
}} }}
> >
<CloseIcon fontSize="small" /> <CloseIcon fontSize="small" />
</IconButton> </IconButton>
<CardActionArea sx={{ width: '100%', height: '100%' }}> <CardActionArea sx={{ width: "100%", height: "100%" }}>
<CardMedia <CardMedia
component="img" component="img"
image={item.src} image={item.src}
alt={item.title} alt={item.title}
sx={{ width: '100%', height: '100%', objectFit: 'cover' }} sx={{
width: "100%",
height: "100%",
objectFit: "cover",
}}
/> />
</CardActionArea> </CardActionArea>
</Card> </Card>
@ -241,7 +282,12 @@ function PostCreation(){
value.map((tags: string, index: number) => { value.map((tags: string, index: number) => {
const { key, ...itemProps } = getItemProps({ index }); const { key, ...itemProps } = getItemProps({ index });
return ( return (
<Chip variant="outlined" label={tags} key={key} {...itemProps} /> <Chip
variant="outlined"
label={tags}
key={key}
{...itemProps}
/>
); );
}) })
} }
@ -249,15 +295,24 @@ function PostCreation(){
<TextField <TextField
{...params} {...params}
variant="outlined" variant="outlined"
color='primary' color="primary"
label="Tags" label="Tags"
placeholder="Add Tags" placeholder="Add Tags"
/> />
)} )}
/> />
<div className="create-buttons"> <div className="create-buttons">
<ButtonPrimary style="secondary" label="Cancel" type="button" onClick={onCancel} ></ButtonPrimary> <ButtonPrimary
<ButtonPrimary style="primary" label="Post" type="submit" ></ButtonPrimary> style="secondary"
label="Cancel"
type="button"
onClick={onCancel}
></ButtonPrimary>
<ButtonPrimary
style="primary"
label="Post"
type="submit"
></ButtonPrimary>
</div> </div>
</div> </div>
</form> </form>