Home > database >  How to dynamically add method calls in a for loop?
How to dynamically add method calls in a for loop?

Time:09-13

I'm absolutly stuck trying to dynamically add object methods in a for loop to an already existing object/class. I want to dynamically add the order method for every object existing in the contactsSorter array from within a for loop.

I've tried it with forEach, with setting the query = variable in the for loop and without. Making it to a function and looked for similar cases but wasn't able to fix the issue that it seems to overwrite the query in the for loop.

Supabase Docs

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

// Create a single supabase client for interacting with your database
const supabase = createClient(
  'https://xyzcompany.supabase.co',
  'public-anon-key'
)
// Initialize array to loop over
const contactsSorter = [
    {
      order: "ascend",
      field: "first_name",
      columnKey: "first_name",
    },
    {
      order: "ascend",
      field: "created_at",
      columnKey: "created_at",
    },
];

// Initialize variable i want to modify in for loop
let query = supabase.from("contacts").select("*", { count: "exact" });

if (contactsSorter.length > 0) {
  // Here I want to dynamically add the order by clause to the query  
  for (let i = 0; i < contactsSorter.length; i  ) {
    query = query.order(contactsSorter[i].field, {
      ascending: contactsSorter[i].order === "ascend" ? true : false,
    });
  }
} else {
  query = query.order("first_name", {
    ascending: true,
  });
}

let { data: contacts, error, count } = await query;

CodePudding user response:

In your example of contactsSorter you have exactly 1 element in this array - another array. And this another array consists of two objects. Apparently you're supposed to have two objects right in contactsSorter, so it should be

const contactsSorter = [
    {
      order: "ascend",
      field: "first_name",
      columnKey: "first_name",
    },
    {
      order: "ascend",
      field: "created_at",
      columnKey: "created_at",
    }
];

CodePudding user response:

since .order function is an asynchronous function, you will have to use async await or .then syntax to use the value returned by query so you should modify your for loop like this:

  for (let i = 0; i < contactsSorter.length; i  ) {
    query = query.then(async res => {
      const data = await res.order(contactsSorter[i].field, {
        ascending: contactsSorter[i].order === "ascend" ? true : false,
      });
      return data;
    });
  }

CodePudding user response:

I found out that my initial code works like charm. It was just a state dependency missing in my code which caused it to not update. So my original code is correct as it is.

  • Related