CoolFace
Apppublic

kunjasd/anycoder-36bad3f9

sourceHugging Faceupdated 10mo agoView on Hugging Face
0likes
PostForm.jsx91 linesDownload Raw Back to components
1import { useState } from 'react';2import { useSession } from 'next-auth/react';3import { useRouter } from 'next/router';4 5export default function PostForm({ onPostCreated }) {6  const [content, setContent] = useState('');7  const [image, setImage] = useState(null);8  const [loading, setLoading] = useState(false);9  const { data: session } = useSession();10  const router = useRouter();11 12  const handleSubmit = async (e) => {13    e.preventDefault();14    if (!content.trim() || !session) return;15 16    setLoading(true);17 18    try {19      const formData = new FormData();20      formData.append('content', content);21      if (image) {22        formData.append('image', image);23      }24 25      const response = await fetch('/api/posts', {26        method: 'POST',27        body: formData,28      });29 30      if (response.ok) {31        const newPost = await response.json();32        setContent('');33        setImage(null);34        onPostCreated(newPost);35      }36    } catch (error) {37      console.error('Error creating post:', error);38    } finally {39      setLoading(false);40    }41  };42 43  if (!session) {44    return (45      <div className="bg-white rounded-lg shadow-md p-4 mb-4">46        <p className="text-center">47          Please{' '}48          <button49            onClick={() => router.push('/login')}50            className="text-primary hover:underline"51          >52            login53          </button>{' '}54          to create a post.55        </p>56      </div>57    );58  }59 60  return (61    <div className="bg-white rounded-lg shadow-md p-4 mb-4">62      <form onSubmit={handleSubmit}>63        <textarea64          value={content}65          onChange={(e) => setContent(e.target.value)}66          placeholder="What's on your mind?"67          className="w-full p-2 border rounded-md focus:outline-none focus:ring-2 focus:ring-primary mb-2"68          rows="3"69          required70        />71 72        <div className="flex items-center justify-between">73          <input74            type="file"75            accept="image/*"76            onChange={(e) => setImage(e.target.files[0])}77            className="text-sm"78          />79 80          <button81            type="submit"82            disabled={loading}83            className="bg-primary text-white px-4 py-2 rounded-md hover:bg-secondary transition-colors disabled:bg-gray-400"84          >85            {loading ? 'Posting...' : 'Post'}86          </button>87        </div>88      </form>89    </div>90  );91}