Giter Club home page Giter Club logo

supabase-swr's Introduction

supabase-swr

A React library to use supabase-js with swr.

Install

Using npm.

npm install supabase-swr supabase-js swr

Using yarn.

yarn add supabase-swr supabase-js swr

Usage

Crate a supabase client and pass it to the SwrSupabaseContext.Provider.

import { createClient } from 'supabase-js';
import { SwrSupabaseContext } from 'supabase-swr';

const client = createClient('https://xyzcompany.supabase.co', 'public-anon-key');

function App() {
  return (
    <SwrSupabaseContext.Provider value={client}>
      <Routes />
    </SwrSupabaseContext.Provider>  
  )
}

Now you can use in any component the api of supabase-swr.

import React from 'react';
import { useClient, useSelect, useQuery } from 'supabase-swr';

type Todo = {
  id: string,
  name: string,
  created_at: string,
};

const Todos = () => {
  const todosQuery = useQuery<Todo>('todos', {
    filter: (query) => query.order('created_at', { ascending: false }),
  }, []);
  const {
    data: {
      data: todos,
    },
    mutate,
  } = useSelect(todosQuery, {
    // any swr config
    revalidateOnMount: true,
    suspense: true,
  });
  return (
    <ul>
      {todos.map((todo: Todo) => (
        <li key={todo.id}>
          {todo.name}
        </li>
      ))}
    </ul>
  );
}

References

API

hooks

useClient

Retrieve the supabase-js client instance provided to SwrSupabaseContext.Provider.

export default function (props) {
  const client = useClient();
  // ...
  return (<>...</>)
}

useQuery

Create a Query to use with useSelect and other hooks. The created query is also a swr key and can be used with mutate.

type Todo = {}

export default function (props) {
  const query = useQuery<Todo>('todos', {
    // the filter ro apply to the query
    filter: (q) => q.order('created_at', { ascending: false }),
    head: false,
    count: 'exact',
  });
  const {
    data
  } = useSelect(selectKey, {
    // swr config here
  });
  // ...
  return (<></>)
}

useSelect

Retrieve the table data requested. Return and SwrResponse.

type Todo = {}

export default function (props) {
  const query = useQuery<Todo>('todos', {
    // the filter ro apply to the query
    filter: (q) => q.order('created_at', { ascending: false }),
    head: false,
    count: 'exact',
  });
  const {
    data
  } = useSelect(query, {
    // swr config here
  });
  // ...
  return (<></>)
}

useSession

Subscribe to authStateChange event and always return the current session. Useful to use inside component that need to change when the user sign-in or sign-out.

export default function (props) {
  const session = useSession();
  if (!session) return <>Need to sign-in to access this feature</>
  return (<>...</>)
}

createQuery

Create a global Query to use with useSelect and other hooks. The created query is also a swr key and can be used with mutate.

import { useSWRConfig } from 'swr';
import { useState } from 'react';
import { createClient } from 'supabase-js';
import { SwrSupabaseContext, useSelect, createQuery } from 'supabase-swr';

const client = createClient('https://xyzcompany.supabase.co', 'public-anon-key');

type Todo = {
  id: string,
  name: string,
  created_at: string,
}

const todosQuery = createQuery<Todo>('todos', {
  columns: '*',
  // the filter ro apply to the query
  filter: (q) => q.order('created_at', { ascending: false }),
})

function AddTodoForm() {
  const { mutate } = useSWRConfig()
  const client = useClient()
  const [todoName, setTodoName] = useState('')
  const addTodo = () => {
    client.from<Todo>('todos').insert({
      name: todoName,
    }).then(() => {
      // update the todosQuery inside the TodosList
      mutate(todosQuery)
      setTodoName('')
    })
  }
  return (
    <form name="add-todo">
      <input name="todo-name" value={todoName} onChange={(e) => setTodoName(e.target.value)} />
      <button onClick={addTodo}>
        Add Todo
      </button>  
    </form>
  )
}

function TodosList() {
  const {
    data: {
      data: todos,
    },
  } = useSelect(todosQuery, {
    // swr config here
  });
  // ...
  return (
    <ul>
      {todos.map((todo: Todo) => (
        <li key={todo.id}>
          {todo.name}
        </li>
      ))}
    </ul>
  );
}

export default function App() {
  return (
    <SwrSupabaseContext.Provider value={client}>
      <TodosList />
      <AddTodoForm />
    </SwrSupabaseContext.Provider>
  )
}

Inspired by react-supabase.

supabase-swr's People

Contributors

alfredosalzillo 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

Watchers

 avatar  avatar

supabase-swr's Issues

Compatibility with supabase-js v2

Is this library compatible with version 2.x of the supabase-js lib? I'm getting an error when using useSelect. The peer dependency is not pinned to v1, so I'm thinking this is probably the problem?

`useQuery` not exported in NPM-package

When trying to import useQuery from supabase-swr, no function is actually available. This can be verified by doing an install of the latest version from NPM and checking the installed module.

Screenshot 2021-10-26 at 23 38 22

How works mutate

Thanks for this project, could you please make a sample for mutate?

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.