0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

supabaseでデータを扱おう

0
Posted at

1.はじめに

小耳にはさんだので簡単に触ってみます。

2.Supabaseとは

Supabaseとは、PostgreSQLをベースにしたオープンソースのサービスのようです。
わざわざ自分で作ることなく簡単にデータベースが導入できるそうです。

3.データベースの作成

アカウント登録

まずはアカウント登録ということで、公式サイトからアカウントから作ります。
アカウントを作成し、もろもろ進めていくと、プロジェクトホームまで行くことができました。

テーブルの作成

サイドバーで「SQL Editor」を選択し、テーブルをSQLで作成していきます。
SQLを入力し、右上の「Run」で実行

create table users (
  id bigint generated by default as identity primary key,
  title text not null,
  hobby text default null
);

次はデータを入れる。

insert into users (title, hobby)
values
  ('yamada', 'travel'),
  ('suzuki', 'music');

次にサイドバーで「table editor」に移動し、反映されているかを確認します。

image.png

4. プログラムからデータを扱う

※今回はvite+Reactのアプリを用います。

supabase用のライブラリを入れます

$ npm install @supabase/supabase-js

supabase側でテーブルを参照するための設置が必要なので、権限を作成します。

grant select on public.users to anon;

alter table public.users enable row level security;

create policy "public can read"
on public.users
for select
to anon
using (true);

プロジェクトルート下に.env.localを作成して、以下を設定してください

VITE_SUPABASE_URL=ここにProject URL
VITE_SUPABASE_PUBLISHABLE_KEY=ここにPublishable key

クライアント用のソースを./src下に用意します。

sbClient.js
import { createClient } from '@supabase/supabase-js'

const supabaseUrl = import.meta.env.VITE_SUPABASE_URL
const supabasePublishableKey =
  import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY

export const supabase = createClient(
  supabaseUrl,
  supabasePublishableKey
)

App.jsxを書き換えます。

App.jsx
import { useEffect, useState } from 'react'
import { supabase } from './sbClient'

function App() {
  const [users, setUsers] = useState([])

  useEffect(() => {
    const getUsers = async () => {
      const { data, error } = await supabase
        .from('users')
        .select('*')

      if (error) {
        console.error(error)
        return
      }

      setUsers(data)
    }

    getUsers()
  }, [])

  return (
    <div>
      <h1>users</h1>

      <ul>
        {users.map((user) => (
          <li key={user.id}>
            {user.title} "さんの趣味は" {user.hobby}
          </li>
        ))}
      </ul>
    </div>
  )
}

export default App

参照出来ました。

image.png

5.まとめ

firebase(僕はあんまり知らない)の代替として注目されているSupabaseのを触ってみた記事でした。quickstartもあり、導入としては触りやすかったです。今回データベースとしての紹介でしたが、その真価は認証やストレージとしても使える点にあるようなので、今後どこかのタイミングで使ってみたいです。SQLがある程度使えるなら使ってみてみいいかなという印象でした。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?