Giter VIP home page Giter VIP logo

use-supabase's Introduction

Use Supabase

NPM

A simple package to boost your supabase consumer app.

// get automatic SWR revalidation on a whole table or a specific column in it
const { data: siteData } = useTable('site', '*')
const { data: siteIdData } = useTable('site', 'site_id')

// grab the client to doing anything you want.
const client = useSupabase()

// create a query and use all the postgres query options
const query = useSupabase().from('site').select('*')
// pass that query to useQuery and get automatic SWR revalidation on it.
const { data: queryData } = useQuery(query)

Initialize Supabase

To get access to the hooks first pass use the SupabaseContextProvider at the root of your app.

Create-React-App

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import { SupabaseContextProvider } from 'use-supabase'

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

const supabase = createClient('supabase-url', 'supabase-anon-key')

ReactDOM.render(
  <React.StrictMode>
    <SupabaseContextProvider client={supabase}>
      <App />
    </SupabaseContextProvider>
  </React.StrictMode>,
  document.getElementById('root')
)

reportWebVitals()

Next.js

If you are using Next.js create a custom _app.tsx like explained here.

Hooks

There are a series of hooks that are made available and usable at your convenience.

useSupabase


useSupabase is the most simple hook in this library. It returns the supabase js client from the context.

const { auth, from } = useSupabase()

useTable


useTable implements a stale while revalidate strategy. It is a convenient hook to quickly get all information from a table and revalidating the data with the best web performance principles. It will default to getting all the columns on a table but you can pass a select object to specify more details in the query.

const { data } = useTable('users', '*')

useQuery


useQuery gives you the same SWR capacities as useTable but gives you complete granular control on the query you pass.

const query = useSupabase().from('users').select('*').eq(...)
const { data } = useQuery(query)

useUser (deprecated)

useUser gives you access to the supabase client user. While it works in all React applications. If you are using a metaframework like Next.js or Remix, you might prefer to use the supabbase auth helpers.

The context will make avaialble to the hooks the client and the user so that you can use it anywhere along the react component tree.

use-supabase's People

Contributors

guibibeau avatar jgillich avatar peterferguson avatar sampl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

use-supabase's Issues

Query data in Nextjs

What would be the best way to query data in a Nextjs app?

It seems that you still need to wrap the query in an async function unless I'm missing something? Perhaps an example on how to use the query could help.

It would be great if we could do something like const { data, loading } = useSupabase(query)

React v17 support

Thanks for the work on this lib. Any chance you've thought about React v17 support? I get the following warnings when using the latest CRA version since it uses [email protected].

15:51:17.628  	warning " > [email protected]" has incorrect peer dependency "react@>= 16.8.0 < 2".
15:51:17.629  	warning " > [email protected]" has incorrect peer dependency "react-dom@>= 16.8.0 < 2".

Realtime / subscriptions

Love this library, using it right now. The basis on SWR is key and so great especially for SWR's { keepPreviousData: true }. Game changer, no more blank flashes in toggling through UI lists.

Looking at this:

https://swr.vercel.app/docs/subscription

and supabase's realtime...

Could we implement a useSubscription and useRealtime() hook? similar to the react-supabase library (which is still stuck at supabase v1)

useSubscription = () => handles incremental updates
useRealtime = () => returns the query bulk rows and then processes any changes made to revalidate

Happy to open a PR with some thoughts

authentication issue

Hi there, thanks for the useful hook.
I'm not sure if my issue regarding the auth is related to this hook or it needs to be escalated to supabase. Let me know!

So, I wrote these two hooks.

function useRedirectToDashboard() {
  const { auth } = useSupabase();
  const router = useRouter();
  useEffect(() => {
    if (auth.user()) {
      router.push("/projects");
    }
  }, [auth]);
}

function useSecure() {
  const router = useRouter();
  const { auth } = useSupabase();
  useEffect(() => {
    if (!auth.user()) {
      router.push("/sign_in");
    }
  }, [auth]);
}

As the names imply, I use useSecure at the beginning of pages that require login. I use useRedirectToDashboard at /sign_in page, so that when a user is already signed in, then so that they can be redirected to the dashboard.

I'm having two issues:

  1. After a certain amount of time, I get back to my website, and I guess the session is expired. And useSecure doesn't work. It still has auth.user() so it won't redirect to /sign_in page. However, please correct me if I'm wrong, isn't it something I should refresh the token and keep the session alive instead of sending the user to the sign in page? I'm not so knowledgeable on this topic.

  2. In many cases, when (1) happens, I'm redirected to sign-in page and immediately get redirected back to the dashboard. It means, in that second, auth.user() was falsey and now truthy again.

Thanks for reading!

Tables with realtime enabled break on serialisation in `useQuery`

When using any tables that have realtime enabled and a subscription set on them the swr key serialisation breaks since the key simply uses JSON.stringify(query) and realtime queries have a circular structure.

I think it is because the SupabaseQueryBuilder has the _realtime attribute which is a RealtimeClient & then the client itself has socket which is also RealtimeClient

The error I am receiving:

index.js?1131:214 Uncaught TypeError: Converting circular structure to JSON
    --> starting at object with constructor 'RealtimeClient'
    |     property 'channels' -> object with constructor 'Array'
    |     index 0 -> object with constructor 'RealtimeSubscription'
    --- property 'socket' closes the circle
    at JSON.stringify (<anonymous>)

I have patched locally to use the query.url.href as a simple fix for the swr key as it should contain enough unique information.

Move to react 18 and concurrent features.

React 18 is officially released,

It adds a lot of great support for building isomorphic libraries that useSupabase can benefit from.

We should explore:

  • useExternalSyncStore as a way to move seemlessly from
  • suspend component while they hydrate?

Implement cypress tests

To permit an higher input from the supabase community, we need a process to automate tests and deployments. The first step is establishing a minimum series of tests.

AC:

  • bootstrap a cypress folder
  • bootstrap a vite react application for testing purposes
  • both should be ignored in the npm packge to avoid bloating the lib size
  • run a dummy test for now
  • connect it to a github actions

useTable

Hello ๐Ÿ‘‹

Thanks a lot for starting of this project. This will be super useful. One thing I believe will be super useful would be to add realtime as part of the hook to listen to changes made in your query. I'm not entirely sure what's the best way to do this but adding an options object in the hook like {realtime: true, type: 'INSERT'} would be absolutely amazing.

useEffect(() => {
  // Listen for updates
  if (listener) {
    const listen = supabase
      .from(listener)
      .on('*', (payload) => console.log(payload)) // -> Do something here
      .subscribe();

    return () => {
      listen.unsubscribe();
    };
  }
  return () => {};
}, []);

Here is the realtime doc as a reference: https://supabase.io/docs/client/subscribe

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.