dijonmusters / build-a-twitter-clone-with-the-next.js-app-router-and-supabase

This repo accompanies a free egghead course where we build a Twitter clone with the Next.js App Router and Supabase 🚀
https://egghead.io/courses/build-a-twitter-clone-with-the-next-js-app-router-and-supabase-19bebadb?af=9qsk0a
90 stars 8 forks source link

Refetch of new tweet requires refreshing the page #2

Open d3v-g opened 1 year ago

d3v-g commented 1 year ago

Noticed on video 13 at 4mins 12seconds when you create a new tweet you do not perform a refresh, but the new data is present. Looking at the NextJS Docs looks like a call to revalidatePath is required.

https://github.com/dijonmusters/build-a-twitter-clone-with-the-next.js-app-router-and-supabase/blob/941ae910701d32eebd2e3e3e77ed525dfd22ca28/13-run-authenticated-server-side-mutations-with-next.js-server-actions/app/new-tweet.tsx#L14C6-L14C6

I imported revalidatePath: import { revalidatePath } from "next/cache"

and called: revalidatePath("/") after inserting a tweet and works as expected.

Thanks for your effort on the course, it's great!

kevinhellos commented 3 months ago

Thank you for this solution. I was experiencing this issue before.

Below is the code for those who needs it for reference.

// new-tweet.tsx

import { createServerActionClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import { revalidatePath } from "next/cache"

export default function NewTweet() {

    const addTweet = async (formData: FormData) => {
        "use server";
        const title = String(formData.get("title"));
        const supabase = createServerActionClient<Database>({ cookies });
        const { data: { user } } = await supabase.auth.getUser();

        if (user) {
            await supabase
            .from("tweets")
            .insert({ title, user_id: user.id });
            revalidatePath("/");
        }
        // console.log("Form submitted...");
    }

    return (
        <form action={addTweet}>
            <input type="text" name="title" className="bg-inherit" required/>
        </form>
    )
};