Skip to content

Mutations similar to resources #394

@adam-kov

Description

@adam-kov

Describe the feature in detail (code, mocks, or screenshots encouraged)

It'd be great to have another utility called mutation or similar, that'd be responsible for create, update, and delete requests. We have resource for async data fetching, but mutations usually happen on user event (mouse click, key press, form submit, etc.), and not reactively.

Resources can be set up to handle non GET requests as well, but it's not as nice a dev experience. That's why I'm thinking of adding a mutation utility (name is up for debate), inspired by TanStack Query. It would have most of the properties of resource (current, loading, error, mutate), but the callback would run only after calling run() or call().

Example

<script lang="ts">
  import { mutation } from 'runed';

  let id = $state(1);

  const deleteMutation = mutation(
    async (id, { onCleanup, signal }) => {
      const response = await fetch(`api/posts/${id}`, {
        method: 'DELETE',
        signal
      });
      return response.json();
    }
  );
</script>

<form onsubmit={() => deleteMutation.run(id)}>
  <input type="number" bind:value={id} />
  <button type="submit">Delete</button>
</form>

{#if deleteMutation.loading}
  <div>Loading...</div>
{:else if deleteMutation.error}
  <div>Error: {deleteMutation.error.message}</div>
{:else if deleteMutation.success}
  <div>Deleted {deleteMutation.current.id}</div>
{/if}

I'd be more than happy to start working on this, but I wanted to have a discussion before jumping on it. Would it be useful? What are your first thoughts?

What type of pull request would this be?

New Feature

Provide relevant links or additional information.

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    triagePending triage by a maintainer to give it proper labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions