SupabaseS
Supabase4y ago
FTZ

Acceptable method to insert multiple rows

I'm trying to create (x) number of rows in one table and for each of the created rows I want to create (x) number of rows in a different table.

Currently I am doing a bulk insert of the first table and then mapping over the returned data and doing a bulk insert for each iteration on the map.

To me this feels like there should be a better way to accomplish this. Especially when it comes to having to do any updates.

const blockObject = blockArray.map((index) => ({
    name: `Training block ${index + 1}`,
    program_id: programId,
    user_id: currentUser?.id,
    state: 1,
    index: index + 1,
  }));

const createBlocks = async () => {
    const { data, error } = await supabase
      .from('blocks')
      .insert([...blockObject]);

    createDaysPerBlock(data);

    return data;
  };

const createDaysPerBlock = async (trainingBlocks) => {
    const days = trainingBlocks.map(async (block) => {
      const dayObject = dayArray.map((index) => ({
        name: `Day ${index + 1}`,
        block_id: block.block_id,
        index: index + 1,
        program_id: programId,
      }));

      const { data, error } = await supabase
        .from('block_day')
        .insert([...dayObject]);

      return data;
    });

    const result = await Promise.all(days);
    return result;
  };
Was this page helpful?