Next.js Discord

Discord Forum

revalidate after change to supabase

Unanswered
European anchovy posted this in #help-forum
Open in Discord
European anchovyOP
How can I revalidate my UI after I made a modification to my database ? I am not fetching anything so I don't see how to use the revalidateTag...and even if I were I still don't think this would be the best solution. I'm making a twitter clone, so my /home path is an infinite feed of tweets. I am trying to update the UI when I like and dislike a post. The problem is that I only managed to revalidate the entire path. How could I fix this ? revalidating the entire path looks very weird for a split second, because everything moves.

"use client";

import { likeTweet, unlikeTweet } from "@/lib/supabase/mutations";
import { createClientComponentClient } from "@supabase/auth-helpers-nextjs";
import { useTransition } from "react";
import { BsHeart, BsHeartFill } from "react-icons/bs";

const Like = ({ tweet }: { tweet: TweetWithAuthor }) => {
  let [isLikePending, startTransition] = useTransition();
  const supabase = createClientComponentClient<Database>();

  const handleLike = async () => {
    const {
      data: { user },
    } = await supabase.auth.getUser();

    if (!user) {
      return;
    } else {
      startTransition(() => {
        if (tweet.user_has_liked_tweet) {
          // dislike
          unlikeTweet({ tweetId: tweet.id, userId: user.id });
        } else {
          // like tweet
          likeTweet({ tweetId: tweet.id, userId: user.id });
        }
      });
    }
  };

  return (
    <button
      disabled={isLikePending}
      onClick={handleLike}
    >
        {tweet.likes}
    </button>
  );
};

export default Like;


export const likeTweet = async ({
  tweetId,
  userId,
}: {
  tweetId: string;
  userId: string;
}) => {
  await supabase.from("likes").insert({
    user_id: userId,
    tweet_id: tweetId,
  });

  revalidatePath("/home");
};

1 Reply

European anchovyOP
I was thinking...I was trying to follow along a tutorial and it made no sense at all to revalidate the entire path to update the ui for one like. Another solution that I've found was to use an experimental useOptimistic hook. But it's experimental AND I don't understand how it works. So I've made 2 useStates for isLiked and likeCount. This lets me update the UI changes to the Like component and then I change it in the supabase db. Is this a good approach ? what is the point of using somethign like useOptimistic ?