Search code examples
javascriptsupabasesupabase-database

How do I fetch Multiple Specific Rows in Supabase JS?


I have 2 tables Clients and Contacts

I have a table with a cell with specific user IDs in the client table called "contacts"
image

How do I fetch the specific rows from the contacts table from the contacts array found in the client table?

Getting the array is easy enough

let associatedContactsArray = [];

async function getAssociatedContactsID() {
        const { data: contacts, error } = await supabaseClient
            .from('clients')
            .select('contacts')
            .eq('id', $clientID);
        if (contacts) {
            const [fetchedContacts] = contacts;
            if (fetchedContacts.contacts != null) {
                associatedContactsArray = fetchedContacts.contacts;
                hasAssociatedContacts = true;
                console.log('ASSOCIATED CONTACTS', associatedContactsArray);

                getAssociatedContacts();
            } else {
                console.log('THERE ARE NO CONTACTS');
                hasAssociatedContacts = false;
            }
        }

        if (error) {
            console.log('ERROR GETTING ASSOCIATED CONTACTS', error);
        }
    }

The following does not work.

    async function getAssociatedContacts() {
        const { data: contacts, error } = await supabaseClient
            .from('contacts')
            .select('*')
            .filter('id', 'in', { associatedContactsArray });
        if (contacts) {
            const [fetchedContacts] = contacts;
            if (fetchedContacts.contacts != null) {
                console.log('GOT CONTACT DETAILS');
                console.log('CONTACTS', contacts);
            } else {
                console.log('NO CONTACT DETAILS');
                hasAssociatedContacts = false;
            }
        }

        if (error) {
            console.log('ERROR GETTING ASSOCIATED CONTACTS', error);
        }
    }

I get the error: { "code": "PGRST100", "details": "unexpected \"[\" expecting \"(\"", "hint": null, "message": "\"failed to parse filter (in.[object Object])\" (line 1, column 4)" }

Referencing Match the Filter: https://supabase.com/docs/reference/javascript/filter


Solution

  • You can use the in filter for this

    const { data, error } = await supabase
      .from('contacts')
      .select()
      .in('id', associatedContactsArray)