0

I been trying to get the hang of supabase as a new dev and it took a while to understand. I don't think my code is efficient event though it works. Any help would be greatly appreciated!

My current store looks like this

import { writable } from 'svelte/store';
import supabase from '$lib/db';

export const todos = writable([]);
export const task = writable('');
export const price = writable();

export const getTodos = async () => {
    let { data, error } = await supabase.from('todos').select('*');
    if (!error) {
        todos.set(data);
    }
};

export const deleteTodos = async (id) => {
    const { data, error } = await supabase.from('todos').delete().match({ id });
    if (!error) {
        await getTodos();
    }
};

export const insertTodos = async (task, price) => {
    const { data, error } = await supabase
        .from('todos')
        .insert([{ task, isCompleted: false, price }]);
    if (!error) {
        await getTodos();
        lol.set(true);
    }
};

export const updatePost = async (task, price, id) => {
    const { data, error } = await supabase.from('todos').update({ task, price }).match({ id });
    if (!error) {
        await getTodos();
    }
};
export const toggle = async (id, isCompleted) => {
    const { data, error } = await supabase
        .from('todos')
        .update({ isCompleted: !isCompleted })
        .match({ id });
    if (!error) {
        await getTodos();
    }
};

1 Answers1

0

Not sure what you're exactly trying to achieve, but you could just make those CRUD functions part of the store:

// store.js
function todoStore() {
  const store = writable([])

  function deleteTodo() { ... }
  function insertTodo() { ... }
  // ...and all your other methods

  return {
    subscribe: store.subscribe,
    insert: insertTodo,
    delete: deleteTodo,
  }
}

export default todoStore()

You can use this store then in your component like this:

  import todos from 'store.js'

  // Get value of store
  $todos

  // Delete todo
  todos.delete(id)

  // Insert todo
  todos.insert({ ... })

Note that you can give the store constructor a function that executes when it receives its first subscriber, see docs. This is helpful to init a store or remove any listeners when the store is being destroyed.

Svelte's store contract is important to understand: as long as you have a subscribe method, you can design your stores in any way you like.

b2m9
  • 591
  • 2
  • 9