Pass a value from an api into an object as to insert a new row into the database

Viewed 83

Using type=radio along with bind:group as shown in my example this will add the row to the database, but it only works for 1 entry plus the user needs to check the radio. Staring with just adding 1 correctly is a good start, but my goal is to add the rows to the database (supabase) in bulk when the user clicks the button as log as the user enters a wagerAmount then the form should display the details from the api in my example it is {game.home} {game.home_spread}. I want to insert spread but cant simply use bind:value.

let wagerAmount = '';
let spread = 0;


const addNewWager = async () => {
    try {
        const { data, error } = await supabase
            .from("wager")
            .insert([{ risk: wagerAmount, made_wager: $user.id, spread: spread}]);
        wagerAmount = "";
        } catch (err) {
        console.log(err);
        }
    };

    <Card>
        <h2 slot="title">Straight Action</h2>
        <ul slot="content">
            {#each nflState.filter(game => game.isHomeSpread) as game (game.id)}
            <li
                    animate:flip
                    in:receive={{key: game.id}}
                    out:send={{key: game.id}}
                >
            <form class="">
             <input type="text" bind:value={wagerAmount} />
             <label>{game.home} {game.home_spread}</label>
             <input type=radio bind:group={spread} name="spread" value={game.home_spread}>
            </form>
            </li>
            {/each}
        </ul>
    </Card>
    </div>
     <button on:click={() => addNewWager()} class="">Bulk Submit</button>
</div>
2 Answers

In order to bulk create/insert, it is necessary to pass all the values in the insert query as an array:

    const { data, error } = await supabase
  .from('wager')
  .insert([
    { risk: wagerAmount, made_wager: $user.id, spread: spread1},
    { risk: wagerAmount, made_wager: $user.id, spread: spread2},
  ])

If you don't want to wait for the results of the call, then you can use then:

.then(console.log)

The answer was to use function onSubmit(e: { target: HTMLFormElement; })

Related