Search code examples
javascriptsveltekitreactive

Form submit and on:click from the same button in SvelteKit


I'm trying to implement a "follower" functionality for an app. I have a table in my DB to track which Users are following which, and on each user's page, I want there to be a button to follow that user. I have tied this button to a reactive variable so that the state of the button (saying "Follow User" if you are not following and "Unfollow User" if you are) will update automatically.

The following is how I've opted to do this, where isFollowing is the reactive variable.


          <!-- Only show "add follower" button if the page is not your own user page AND you are not already following -->
          {#if user.id != localUserId && !isFollowing}
            <TableBodyCell>
              <form method="POST" action="?/followUser" on:click={() => toggleIsFollowing()}>
                <Button type="submit"> 
                  <PlusSolid class="h-10 w-10 fill-current text-[#333333] hover:cursor-pointer" />
                </Button>
                <Heading customSize="mb-2 text-2xl font-extrabold" style="color:#333333"> Follow </Heading>
              </form>
            </TableBodyCell>
          {/if}

          <!-- Show unfollow button if you are following -->
          {#if isFollowing}
            <TableBodyCell>
              <Button type="submit"> 
                <MinusSolid class="h-10 w-10 fill-current text-[#333333] hover:cursor-pointer" on:click={() => toggleIsFollowing()}/>
              </Button>
              <Heading customSize="mb-2 text-2xl font-extrabold" style="color:#333333"> Unfollow </Heading>
            </TableBodyCell>
          {/if} 

However, when I set up the Button to both submit the form and toggle the reactive variable via on:click, the on:click is the only performed, and the form not submitted. Is there a better way to do this?


Solution

  • If you just use use:enhance on the form, that will send the request asynchronously. If the isFollowing comes from the page data (in a reactive) way, it will update automatically once the action is completed (it invalides & reloads data). So ideally you don't need to do anything else.

    You could customize the enhance by supplying a submit handler, which could be used to do optimistic updates (setting the flag before the request completes).