next.js 如何在React(Next JS)和Apollo中创建数据后获取Id

e5njpo68  于 2022-11-05  发布在  React
关注(0)|答案(3)|浏览(170)

我试图在电子商务网站我试图使我的个人项目的地方订单。我想在我创建的数据或输入的数据后,我已经得到了Id,并将其重定向到orders/[id],然后Id

以下是我的代码:

import React, { useContext, useState } from "react";
import { FETCH_USER_QUERY } from "../util/graphql/Queries";
import { useMutation, useQuery } from "@apollo/react-hooks";
import { AuthContext } from "../context/auth";
import { CartContext } from "../context/cart/CartContext";
import { Form, Button } from "semantic-ui-react";
import { CREATE_ORDER_MUTATION } from "../util/graphql/Mutations";
import { useRouter } from "next/router";

export default function Checkout() {
  const router = useRouter();

  const [cartItems, setCartItems] = useContext(CartContext);
  const [paymentMethod, setPaymentMethod] = useState("");
  const [address, setAddress] = useState("");

  const [createOrder, { data, loading }] = useMutation(CREATE_ORDER_MUTATION);

  const qty = cartItems.map(({ quantity }) => {
    return quantity;
  });

  const cartItemId = cartItems.map(({ id }) => {
    return id;
  });

  function onSubmit() {
    createOrder({
      variables: {
        qty: qty[0],

        products: cartItemId[0],
        paymentMethod: paymentMethod,
        address: address,
      },
    })
      .then(() => {
        setTimeout(() => {
          const { createOrder: order } = { ...data };
          console.log(order?.id);
        }, 500);
      })
  }

  return (
    <>
      <Form onSubmit={onSubmit} className={loading ? "loading" : ""}>
        <h2>Create a Main Category:</h2>
        <Form.Field>
          <Form.Input
            placeholder="Please Enter Address"
            name="address"
            label="Address: "
            onChange={(event) => {
              setAddress(event.target.value);
            }}
            value={address}
          />
          <label>Status: </label>
          <select
            name="category"
            className="form-control"
            onChange={(event) => {
              setPaymentMethod(event.target.value);
            }}
          >
            <option value="Cash On Delivery">Cash On Delivery</option>
            <option value="PayPal">PayPal</option>
            <option value="GCash">GCash</option>
          </select>
          <br />

          <Button type="submit" color="teal">
            Submit
          </Button>
        </Form.Field>
      </Form>
    </>
  );
}

但是在我提交了我输入的数据之后,日志返回给我undefined,但是当我再次输入数据并提交时,它给我的是该数据以前的id。有什么办法可以做到这一点吗?如果你不明白我的意思,请让我知道,我会在评论中解释,或者如果你需要任何代码,我可以给你,我会尽可能透明

qacovj5a

qacovj5a1#

该问题是由过时的关闭引起的。在将setTimeout推入回调队列时,data的对象引用是一个较旧的对象引用。因此,该值从未刷新。您需要通过在相同的先前状态上调度操作或使用useRef来获取较新的值。

xzabzqsa

xzabzqsa2#

除了使用SetTimeOut(),只要成功完成变异,就可以简单地使用Apollo graphql中的onCompleted()函数来执行任何操作。

const [createOrder, { data, loading }] = useMutation(CREATE_ORDER_MUTATION, {
       variables: {

          },

      onCompleted(data) {
          console.log(data) // this is log all queries from the mutation including the ID you need
        // whatever you want to do when the mutation is successful

           router.push({
           pathname: '/any-page',
       query: {CartID: data.cart_id}, // check the console.log to see how the ID is returned });       
 }});
6uxekuva

6uxekuva3#

您忘记从 promise 返回res参数。它应该如下所示:

.then((res) => {
  setTimeout(() => {
    const { createOrder: order } = { ...res };
    console.log(order?.id);
  }, 500);
})

相关问题