React (Next JS) 和 Apollo 创建数据后如何获取 Id

How to get Id after data is created in React (Next JS) and Apollo

我正在尝试在电子商务网站上下订单,我正在为我的个人项目制作。我想在创建数据或输入数据后得到 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>
    </>
  );
}

但是在我提交我输入的数据后,日志 returns 我 undefined,但是当我再次输入数据并提交时,它会给我该数据的先前 ID。有什么办法吗?如果你不明白我的意思请告诉我我会在评论中解释,或者如果你需要任何代码我可以给你我会尽可能透明

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

您忘记了 return 您的 承诺 中的 res 参数。它应该看起来像这样:

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