Home > Enterprise >  How to POST Data to an API in React JS
How to POST Data to an API in React JS

Time:05-23

My goal is to be able to POST the data in my body and the one a user has input on the FORM. When a user clicks submit the data must be sent and I would like to display, Loading, and then the Response from the Server when the post has been made. With some error handling also.

I have tried using Axios and simple POST with error handling, but with no luck.

When I console Results. I see the Server response. But I only want the data to be send only when I click the Submit Button. Not when I load the page.

Below is the example

import React, { useEffect, useState } from "react";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useParams,
  Link,
  generatePath,
} from "react-router-dom";

function Checkout({ cart, setCart, handleChange, countCartItem }) {
  const token = "3bb990f1-5fbe-39bf-a320-8ad11b4bc95c";
  const [result, setResult] = useState([]);

  useEffect(() => {
    const requestOptions = {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${token}`,
      },
      body: JSON.stringify({
        transactionReference: "string",
        paymentMethod: "CreditCard",
        checkoutOrderUrl: "http://www.test.com/",
        user: {
          name: "string",
          msisdn: " 27610983142",
          email: "[email protected]",
        },
        payementMethodDetail: {
          RedirectUrl: "http://www.test.com",
          PurchaseEventWebhookUrl: "http://www.test.com",
        },
        bundle: [
          {
            productCode: "317",
            amount: 50,
            currencyCode: "ZAR",
            quantity: 1,
          },
        ],
      }),
    };
    fetch(
      "https://api.flash-internal.flash-group.com/ecommerceManagement/1.0.0/api/checkout/",
      requestOptions
    )
      .then((res) => res.json())
      .then((json) => setResult(json));
  }, []);

  console.log(result);

  const price = cart.reduce(
    (total, item) => total   item.amount * item.FaceValue,
    0
  );

  const orderTotal = cart.reduce((total, item) =>  price    item.Vat, 0);

  const vat = cart.reduce((total, item) => item.Vat, 12);

  function handleSubmit(e) {
    e.preventDefault();
    const { name, surname, cellphone, email } = e.target.elements;

    const data = {
      name: name.value,
      surname: surname.value,
      cellphone: cellphone.value,
      email: email.value,
      orderTotal,
      cart,
    };

    console.log(data);
  }

  console.log();

  return (
    <>
      <div  style={{ height: "100vh" }}>
        <div >
          <div >
            <article>
              <div >
                <div >
                  <div className="py-4">
                    <Link to="/cart">
                      <span style={{ fontSize: 16, fontWeight: 700 }}>
                        <span>
                          <i ></i>
                        </span>
                        Back to Cart
                      </span>
                    </Link>

                    <br />
                    <span style={{ fontSize: 40, fontWeight: 700 }}>
                      Shipping Information
                    </span>
                  </div>

                  <div style={{ margin: "100px 290px" }}>
                    <h2
                      style={{
                        fontSize: 20,
                        fontWeight: 700,
                        width: "285px",
                        lineHeight: "23px",
                        paddingBottom: 16,
                      }}
                    >
                      Please provide your details to continue to payment
                    </h2>
                    <form onSubmit={handleSubmit}>
                      <label for="staticEmail" className="col col-form-label">
                        First Name
                      </label>
                      <input
                        className="form-control form-control-lg"
                        type="text"
                        placeholder="Your name"
                        id="name"
                      />
                      <label
                        for="staticEmail"
                        className="col-sm-2 col-form-label"
                      >
                        Surname
                      </label>
                      <input
                        className="form-control form-control-lg"
                        type="text"
                        placeholder="Surname"
                        id="surname"
                      />
                      <label
                        for="staticEmail"
                        className="col-sm-2 col-form-label"
                      >
                        Cellphone
                      </label>
                      <input
                        className="form-control form-control-lg"
                        type="text"
                        placeholder="Cellphone"
                        id="cellphone"
                      />
                      <label
                        for="staticEmail"
                        className="col-sm-2 col-form-label"
                      >
                        Email
                      </label>
                      <input
                        className="form-control form-control-lg"
                        type="text"
                        placeholder="Email"
                        id="email"
                      />
                      <br />
                      <input
                        style={{
                          width: "100%",
                          height: 48,
                          fontWeight: 700,
                          borderRadius: 8,
                          border: "solid #97E128 1px",
                          padding: "auto",
                          backgroundColor: "#97E128",
                        }}
                        type="submit"
                        value="Confirm to payment"
                      />
                    </form>
                  </div>
                </div>
              </div>
              <div
                
                style={{ display: "contents" }}
              >
              </div>
            </article>
          </div>
        </div>
      </div>
    </>
  );
}

export default Checkout;

CodePudding user response:

You need to call the API from your handleSubmit function instead of useEffect. useEffect is called when page load and on rerender. Just move your code from useEffect to function and call that function from your handleSubmit with user entered form data.

CodePudding user response:

Move code from useEffect to handleSubmit. Read how the useEffect works because you don't understand it. Make variable isLoading and make it false on default. Make variable responseData and set it to null on default. In jsx make conditional rendering like {isLoading && <Loading_component>}. In jsx make conditional rendering like {responseData && {responseData}} to render the response (I don't know how your response is formatted, you need to modify what I wrote). In handleSubmit before fetch set isLoading to true and inside the fetch in .then set it to false and next to it (still inside .then) set your responseData to response.data. After .then make .catch and inside it handle your errors from api if there are some.

  • Related