honojs / website

Repository for hono.dev
https://hono.dev
68 stars 209 forks source link

Stacks RPC code example #337

Open jwhits opened 2 months ago

jwhits commented 2 months ago

The hono stacks page showing RPC react example with posts and gets is really useful showing how hono and RPC with tanstack query can be used for frontend and backend.

However to get the example working I had to change the way the mutation worked by adding mutationFN. Could be worth updating the page?

Current code example

const mutation = useMutation<
    InferResponseType<typeof $post>,
    Error,
    InferRequestType<typeof $post>['form']
  >(
    async (todo) => {
      const res = await $post({
        form: todo,
      })
      return await res.json()
    },
    {
      onSuccess: async () => {
        queryClient.invalidateQueries({ queryKey: ['todos'] })
      },
      onError: (error) => {
        console.log(error)
      },
    }
  )

Changed to

const mutation = useMutation<
    InferResponseType<typeof $post>,
    Error,
    InferRequestType<typeof $post>['form']
  >({
    // Mutation function
    mutationFn: async (todo) => {
      const res = await $post({
        form: todo,
      });
      return await res.json()
    },

    // Success handler
    onSuccess: async () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] })
    },

    // Error handler
    onError: (error: Error) => {
      console.error(error)
    },
  })