I'm trying to make the place order in the ecommerce website I'm trying to make for my personal project. I wanted after I created the data or input the data I have made I get that Id
and Redirect it to the orders/[id]
then the 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>
</>
);
}
But after I submitted my inputted data the log returns me undefined
, but when I input data again and submit it gives me the previous id of that data. Is there any way to do this? If you don't understand what I mean please let me know I'll explain in the comments, or if you need any code I could give it to you I will be transparent as I can
You forgot to return the res
parameter from your promise. It should look something like this:
.then((res) => {
setTimeout(() => {
const { createOrder: order } = { ...res };
console.log(order?.id);
}, 500);
})