Next.js Discord

Discord Forum

How to reexecute an async function without UseEffect in server component ?

Unanswered
Sun bear posted this in #help-forum
Open in Discord
Sun bearOP
Hey I have a NextJs app where I fetch some comments, and when I post a comment, I want my fetch function to be reexecuted.
Why ?

At this time, when I post a comment, I use router.refresh() to refresh my page, so my component refresh and the fetch function is reexecuted.
But I do not want this refresh anymore, I want my app to be smoother by just reexecute my fetch function when I have posted my comment.

So this is my code where I fetch :

import { getServerSession } from "next-auth";
import { options } from "@/app/api/auth/[...nextauth]/options";
import React, { Suspense } from "react";
import CommentsForm from "./CommentsForm";
import { fetchAllComments } from "@/app/api/Comments/fetchAllComments";
import Skeleton from "react-loading-skeleton";
import "react-loading-skeleton/dist/skeleton.css";
import EspaceComm from "./EspaceComm";





async function FetchCommentRasso({ id }: { id: string }) {
  const session = await getServerSession(options);
  const sessionid = session?.user?.id;
  const nameOfProprio = session?.user?.name;
  const userImage = session?.user?.image;
  const res = await fetchAllComments(id);

  
  

  return (
    <div>
      {res?.length === 0 ? (
        <>
          <p className="p-2 font-bold">
            Dans l&apos;attente de ton commentaire...
          </p>
          <div className="flex p-2 mt-3 gap-2">
            <div className="flex items-end">
              <Skeleton circle height={64} width={64} />
            </div>
            <div className="w-[80%] rounded-2xl p-4 shadow">
              <Skeleton />
              <Skeleton width={"30%"} />
            </div>
          </div>
        </>
      ) : (
        <>
          <EspaceComm res={res} sessionid={sessionid}  />
        </>
      )}

      <CommentsForm
        id0={id}
        nameOfProprio={nameOfProprio}
        userImage={userImage}
        idUser={sessionid}
      />
    </div>
  );
}

export default FetchCommentRasso;

4 Replies

Sun bearOP
And this is the code where I post smth :

"use client";
import React, { useState } from "react";
import { useRouter } from "next/navigation";
import { useSession } from "next-auth/react";
import { Separator } from "@/components/ui/separator";
import { useToast } from "@/components/ui/use-toast";
import { ToastAction } from "@/components/ui/toast";
import Link from "next/link";

function CommentsForm({
  id0,
  nameOfProprio,
  userImage,
  idUser,
}: {
  id0: string;
  nameOfProprio: string;
  userImage: string;
  idUser: string;
}) {
  const { data: session } = useSession();
  const { toast } = useToast();

  const [formData, setFormData] = useState({
    contentOfComment: "",
    idOfRasso: id0,
    nomOfProprio: nameOfProprio,
    profilePic: userImage,
    idOfUser: idUser,
  });
  const router = useRouter();
  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const name = e.target.name;
    const value = e.target.value;

    setFormData((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    if (session) {
      e.preventDefault();
      const res = await fetch("/api/Comments", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(formData),
      });
      router.refresh();
    } else {
      e.preventDefault();
      toast({
        description: (
          <span className="text-sm flex items-center">
            <img src="/Images/crosss.svg" alt="" className="w-6 h-6" />
            <p>Connectez-vous pour accéder à ce service.</p>
          </span>
        ),
        action: (
          <ToastAction altText="Me connecter" className="border-[#FF7E14]">
            <Link href={"/Account"}>Me connecter</Link>
          </ToastAction>
        ),
      });
    }
  };

  return (
    <>
      <Separator className="w-[60%] mx-auto mt-8" />
      <form
        onSubmit={handleSubmit}
        className="flex justify-center gap-3 w-full mt-4  "
      >
        <input
          type="text"
          onChange={handleChange}
          name="contentOfComment"
          className=" border rounded-full p-1 w-96 bg-gray-200 hover:pl-5 ease-in-out duration-300 text-sm pl-4"
          placeholder="Mon message..."
          required
        />
        <button
          type="submit"
          className="flex justify-center items-center border border-gray-200 rounded-full p-2 hover:border-orange-500 hover:text-white ease-in-out duration-200 hover:-rotate-90"
        >
          <img src="/Images/sendd.svg" className="h-6 w-6" alt="send" />
        </button>
      </form>
    </>
  );
}

export default CommentsForm;
I Simply just want my "fetchAllComments" function to be remounted/reexectued when I post a comment on my bdd.
I'm kinda a beginer with NextJS so I would really like to have your help guys since I do not find the solution on internet.
Tonkinese
Invalidate the cache / refetch on success of the post comment action