我有使用remix运行发送数据到服务器的问题-我不确定我完全理解useAction数据是如何工作的。我了解如何使用eloaderdata功能的工作,但当你试图发送数据到服务器我得到错误。
我想做的是发送一个post请求到我的服务器当我点击一个按钮-如果我尝试调用创建购物车在handleCLick事件它说createCart不是一个函数当它是
const submit = useSubmit()
function action({ request }) {
is this where i do my POST api call?
}
async function handleClick(event) {
await createCart(id, amount)
}
似乎找不到任何文档告诉你如何做到这一点?
编辑:点击发送太早
使用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>
)
}