Skip to content
This repository has been archived by the owner on Nov 28, 2023. It is now read-only.

Increase typesafety for mutations #23

Open
gt-codes opened this issue Sep 2, 2022 · 1 comment
Open

Increase typesafety for mutations #23

gt-codes opened this issue Sep 2, 2022 · 1 comment

Comments

@gt-codes
Copy link

gt-codes commented Sep 2, 2022

# Problem

When submitting this mutation, an Unhandled Runtime Error is thrown. next-fetch should let us know there’s not an input with name="content"

// pages/api/todos.swr.ts
export const useCreateTodo = mutation(
  z.object({
    content: z.string(),
  }),
  async ({ content }) => {
    // ...
  }
);
// pages/index.tsx

export default function Home() {
  const mutation = useCreateTodo();
  
  <Form mutation={mutation}>
      <label htmlFor='newTodo'>Add a new todo</label>
      <input
          type='text'
          name='newTodo'
          id='newTodo'			
          placeholder='New todo'
        />
      <button type='submit'>Add todo</button>
  </Form>
}

Solution Description

When using the <Form /> component, there should be typesafety letting the user know they don't have an <input /> that aligns with their mutation's input.

I'd expect the same typesafety if programmatically calling the mutation like so:

const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
  e.preventDefault();
  const values = new FormData(formRef.current as HTMLFormElement);
  const data = Object.fromEntries(values);
  createTodo.trigger(data);
};

CleanShot 2022-09-02 at 15 21 07@2x

This is the error on data being passed to trigger

@Schniz
Copy link
Collaborator

Schniz commented Sep 2, 2022

I can’t think of a way to make a form component statically typed based on its children inputs. Can you? 😞

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants