I want to type the sample code of strip.js, but I don't know how to guess the type.

Asked 2 years ago, Updated 2 years ago, 417 views

I saw in the document that react-stripe-js itself supports TypeScript, but I don't know how to guess what type I installed. I saw an article like CardElementComponent and import, and the consthandleChange=async(event:CardElementComponent)=> red line appeared.
Could you please let me know the details?
Thank you for your cooperation.

import React, {useState, useEffect} from "react";
import {
  CardElement,
  CardElementComponent,
  useStrip,
  useElements
} from "@stripe/react-stripe-js";

export default function CheckoutForm() {
  // Added type to useState.
  const [succeeded, setSucceeded] = useState(false);
  const [error, setError] = useState<string | null>(null);
  // If you set the type of string below to any, you will get the last error.
  const [processing, setProcessing] = useState<string | boolean>(');
  const [disabled, setDisabled] = useState(true);
  const [clientSecret, setClientSecret] = useState(');
  const strip=useStrip();
  construction=useElements();

  useEffect(()=>{
    // Create PaymentIntent as soon as the page loads
    window
      .fetch("/create-payment-intent", {
        method: "POST",
        headers:{
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ items: [{id:"xl-tshirt"}]})
      })
      .then(res=>{
        return res.json();
      })
      .then(data=>{
        setClientSecret(data.clientSecret);
      });
  }, []);

  constcardStyle={
    style: {
      base: {
        color: "#32325d",
        fontFamily: 'Arial, sans-serif',
        fontSmoothing: "antialized",
        fontSize: "16px",
        "::placeholder":{
          color: "#32325d"
        }
      },
      invalid: {
        color: "#fa755a",
        iconColor: "#fa755a"
      }
    }
  };
  // I don't know how to model the event here.
  consthandleChange=async(event)=>{
    // Listen for changes in the CardElement
    // and display any errors as the customer types their card details
    setDisabled(event.empty);
    setError(event.error?event.error.message:"";
  };

  consthandleSubmit=asyncev=>{
    ev.preventDefault();
    setProcessing (true);
    // Again, there is an error in the strip and Object is positively 'null'.
    const payload = wait strip.confirmCardPayment(clientSecret, {
      payment_method: {
        card —elements.getElement (CardElement)
      }
    });

    if(payload.error){
      setError(`Payment failed${payload.error.message}`);
      setProcessing (false);
    } else{
      setError(null);
      setProcessing (false);
      setSuccessed(true);
    }
  };

  return(
    <form id="payment-form" onSubmit={handleSubmit}>
      <CardElement id="card-element" options={cardStyle}onChange={handleChange}/>
      <button
        disabled = { processing | | disabled | | succeeded }
        id="submit"
      >
        <span id="button-text">
          {processing?(
            <div className="spinner" id="spinner"></div>
          ) : (
            "Pay now".
          )}
        </span>
      </button>
      {/* Show any error that happens when processing the payment*/}
      {error&(
        <div className="card-error" role="alert">
          {error}
        </div>
      )}
      {/* Show a success message upon completion*/}
      <pclassName={successed?"result-message":"result-message hidden"}>
        Payment succeeded, see the result in your
        <a
          href={`https://dashboard.stripe.com/test/payments`}
        >
          {" "}
          Stripe dashboard.
        </a> Refresh the page to pay again.
      </p>
    </form>
  );
}

Add

Object is positively 'null'.
I could avoid the error by adding an exclamation point as shown below and doing nothing if null.

consthandleSubmit=async(ev:{preventDefault:()=>void;})=>{
    ev.preventDefault();
    setProcessing (true);
    // I added an exclamation point saying that if strip is null, I would do nothing.
    const payload = wait strip !.confirmCardPayment(clientSecret, {
      payment_method: {
        card: elements!.getElement(CardElement)!
      }
    });

Additional 2

最後のエラーで disabledType 'string | boolean' is not assignable to type 'boolean | undefined'. Type 'string' is not assignable to type 'boolean | undefined'.ts(2322) index.d.ts(2048, 9): The expected type comes from property 'disabled' which is declared here on type 'DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>' (JSX attribute) React.ButtonHTMLAttributes<HTMLButtonElement>.disabled?:boolean | undefined error.

<form id="payment-form" onSubmit={handleSubmit}>
      {/* HandleChange Runs When CardElement Changes*/}
      <CardElement id="card-element" options={cardStyle}onChange={handleChange}/>
      <button
        type = "submit"
        // There is an error here.
        disabled = { processing | | disabled | | succeeded }
        id="submit"
      >

See also

https://stripe.com/docs/payments/integration-builder

It says to import CardElementComponent, but it doesn't say how to use it after that.
https://stackoverflow.com/questions/62680716/what-type-to-use-for-the-cardelement-in-typescript-for-stripe-react-stripe-j

Card Element Documentation https://stripe.com/docs/js/element/events/on_change?type=cardElement

typescript

2022-09-30 21:59

1 Answers

The event type is StripeCardElementChangeEvent.

import {StripeCardElementChangeEvent} from "@stripe/stripe-js";

On VSCode, hover your mouse over onChange.

VSCode

Or try to implement it directly without using variables.

<CardElement
        id="card-element"
        options={cardStyle}
        onChange={(event)=>{}}
      />

Then hover your mouse over the event to see the same description.

Enter a description of the image here

Additional examples are available in the reference.

 if(!stripe||!elements){
      // Stripe.js has not loaded yet.Make sure to disable
      // form submission until Stripe.js has loaded.
      return;
    }

If either is null, implement it so that it cannot be submitted.

For postscript 2, as indicated by the error message,

Type 'string | boolean' is not assigned to type 'boolean | undefined'.

This is because you are trying to substitute a value of type string|boolean for type disabled.
(The information of the type can be found in the VSCode hover display as described above.)

 const [processing, setProcessing] = useState<boolean>(false);


2022-09-30 21:59

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.