Next.js Discord

Discord Forum

useOptimistic

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
"use client";

import { useEffect, useState, experimental_useOptimistic } from "react";
import { Comment } from "@prisma/client";
import { subscribeAbly } from "@/lib/ably";
import { useSession } from "next-auth/react";

type OptimisiticComment = Comment & { pending: boolean };

export default function Comments({ reviewId }: { reviewId: string }) {
    const [comments, setComments] = useState<Comment[]>([]);
    const [optimisticComments, setOptimisticComments] =
        experimental_useOptimistic<OptimisiticComment[]>(
            comments as OptimisiticComment[]
        );
    const [sendText, setSendText] = useState<string>("");
    const { data, status } = useSession();

    const initComments = async () => {
        const res = await fetch(`/api/comments/review/${reviewId}`);
        const comments = await res.json();
        setComments(comments);
        await subscribeAbly(reviewId, (comment: Comment) => {
            if (comment.authorId === data?.user.id) return;
            setComments((prev) => [...prev, comment]);
        });
    };

    const sendComment = async () => {
        const comment: OptimisiticComment = {
            text: sendText,
            authorId: data?.user.id as string,
            reviewId,
            createdAt: new Date(),
            id: crypto.randomUUID(),
            pending: true,
        };
        setOptimisticComments((prev) => [...prev, comment]);
        const res = await fetch(`/api/comments`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                reviewId,
                text: sendText,
            }),
        });
        setComments((prev) => [...prev, comment]);
    };

    useEffect(() => {
        initComments();
    }, []);

    return (
        <div>
            <h2>Comments:</h2>
            <div>
                {optimisticComments.map((comment) => (
  

7 Replies

Sun bearOP
                  <div
                        className={comment.pending ? "opacity-50" : ""}
                        key={comment.id}
                    >
                        <p>{comment.text}</p>
                    </div>
                ))}
            </div>
            <input
                onChange={(e) => setSendText(e.target.value)}
                type="text"
                className="p-5 border"
            />
            <button onClick={sendComment}>Send Comment</button>
        </div>
    );
}
i dont even understand why i needed optimistic hook
can you help me
i want to add comment to review
but i dont know how to use correctly
this hook or if i need it
i dont get it why it is helpful