使用 remix run 将数据发送到服务器

mar*_*tty 2 remix.run

我在使用 remix run 将数据发送到服务器时遇到问题 - 我不确定我是否完全理解 useAction 数据的工作原理。我了解 useLoaderData 函数的工作原理,但是当您尝试将数据发送到服务器时,我会收到错误。

我想要做的是当我单击按钮时向我的服务器发送一个发布请求 - 如果我尝试在handleCLick事件中调用create cart,它会说createCart不是一个函数,当它是时

const submit = useSubmit()

 function action({ request }) {
  is this where i do my POST api call?

}

async function handleClick(event) {
    await createCart(id, amount)
  }
Run Code Online (Sandbox Code Playgroud)

似乎找不到任何文档告诉您如何执行此操作?

Kil*_*man 7

编辑:太早点击发送

使用 Remix,操作始终在服务器上运行。这是当您 POST 到路线时 Remix 将调用的方法。

// route.tsx

import { json, type ActionArgs, type LoaderArgs } from '@remix-run/node'
import { Form, useActionData, useLoaderData, useSubmit } from '@remix-run/react'
import { createCart } from '~/models/cart.server' // your app code
import { getUserId } from '~/models/user.server' 

// loader is called on GET
export const loader = async ({request}: LoaderArgs) => {
  // get current user id
  const id = await getUserId(request)
  // return
  return json({ id })
}

// action is called on POST
export const action = async ({request}: ActionArgs) => {
  // get the form data from the POST
  const formData = await request.formData()
  // get the values from form data converting types
  const id = Number(formData.get('id'))
  const amount = Number(formData.get('amount'))
  // call function on back end to create cart
  const cart = await createCart(id, amount)
  // return the cart to the client
  return json({ cart })
}

// this is your UI component
export default function Cart() {
  // useLoaderData is simply returning the data from loader, it has already
  // been fetched before component is rendered. It does NOT do the actual 
  // fetch, Remix fetches for you
  const { id } = useLoaderData<typeof loader>()
  // useActionData returns result from action (it's undefined until
  // action has been called so guard against that for destructuring
  const { cart } = useActionData<typeof action>() ?? {}
  // Remix handles Form submit automatically so you don't really
  // need the useSubmit hook
  const submit = useSubmit()
  const handleSubmit = (e) => {
    submit(e.target.form)
  }
  return (
    <Form method="post">
      {/* hidden form field to pass back user id *}
      <input type="hidden" name="id"/>
      <input type="number" name="amount"/>
      {/* Remix will automatically call submit when you click button *}
      <button>Create Cart</button>
      {/* show returned cart data from action */}
      <pre>{JSON.stringify(cart, null, 2)}</pre>
    </Form>
  )
}
Run Code Online (Sandbox Code Playgroud)