티스토리 뷰

반응형

[클리커 리뉴얼 01]nextjs+supabase 기본 구성 

 

 참고페이지

https://supabase.com/docs/guides/getting-started/quickstarts/nextjs

 

Use Supabase with Next.js | Supabase Docs

_10 return {JSON.stringify(notes, null, 2)}

supabase.com

 

 

#nextjs+supabase 설치

npx create-next-app -e with-supabase

 

#설치 후 실행

npm run dev

 

 

#supabase로 이동 및 가입 및 DB 생성진행

https://supabase.com/

 

Supabase | The Open Source Firebase Alternative

Build production-grade applications with a Postgres database, Authentication, instant APIs, Realtime, Functions, Storage and Vector embeddings. Start for free.

supabase.com

 

https://supabase.com/dashboard/

프로젝트의 SQL Editor로 이동하여, 아래 쿼리를 입력

 -- Create the table
 create table notes (
   id serial primary key,
   title text
 );

 -- Insert some sample data
 insert into notes (title)
 values
   ('Today I created a Supabase project.'),
   ('I added some data and queried it from Next.js.'),
   ('It was awesome!');

 

#Supabase에서 Database에 Enable Realtime을 체크

 

#사이트에 있는 URL 및 토큰을 .env.example에 업데이트 후 파일명을 .env.local로 변경

 

#프로젝트를 다시 실행 후 화면 보면 제대로 로드되어있음

 

#view를 다음과 같이변경

  import { createClient } from '@/utils/supabase/server';

  export default async function Notes() {
    const supabase = createClient();
    const { data: notes } = await supabase.from("notes").select();

    return <pre>{JSON.stringify(notes, null, 2)}</pre>
  }

 

#페이지 확인 후 구독 로직 추가

'use client'
import { createClient } from '@/utils/supabase/client'
import { useEffect, useState } from 'react'

export default function Page() {
  const [notes, setNotes] = useState<any[] | null>(null)
  const supabase = createClient()

  useEffect(() => {
    const userListener = supabase
      .channel('public:notes')
      .on('postgres_changes', { event: '*', schema: 'public', table: 'notes' }, (payload) =>
        handleAllEventsPayload(payload)
      )
      .subscribe()
    const getData = async () => {
      const { data } = await supabase.from('notes').select()
      setNotes(data)
    }
    getData()
    return () => {
      userListener.unsubscribe()
    }

  }, [])
  function handleAllEventsPayload(payload: any): void {
    // INSERT 이벤트에 대한 처리
    if (payload.eventType === 'INSERT') {
      setNotes((currentNotes) => {
        // 이미 같은 id를 가진 노트가 있는지 확인
        const isExisting = currentNotes?.some(note => note.id === payload.new.id)
        if (!isExisting&&currentNotes != null) {
          // 새로운 노트를 현재 목록에 추가
          return [...currentNotes, payload.new]
        }
        return currentNotes
      })
    }

    // 다른 이벤트 유형에 대한 처리도 여기에 추가할 수 있어
    console.log(payload)
  }

  return <pre>{JSON.stringify(notes, null, 2)}</pre>
}

function handleAllEventsPayload(payload: any): void {
  console.log(payload);
}

 

그러면 supabase나 다른 페이지에서 추가되면 실시간으로 데이터베이스 갱신되는걸 확인 할 수 있다

 

#realtime #supabase #nextjs

반응형
댓글
반응형