medipass/react-payment-inputs

Suggestion to update README section about options for usePaymentInputs

Closed this issue · 0 comments

This might be obvious for people who have more experience with React hooks, but code like this:

function MyComponent() {
  const paymentInputs = usePaymentInputs({
    errorMessages: {
      emptyCardNumber: {
        id: 'CheckoutPage.StepPayment.CreditCardForm.Error.emptyCardNumber',
      },
    },
  });

  ...

  return <Whatever />;
}

will cause an infinite render loop, because errorMessages is a nested object that is recreated on every render, so even though errorMessages is marked as a dependency in useEffect hook used internally by this library, it will use === comparison, always return false and cause re-render.

It can be easily fixed by defining error messages outside of the component:

const ERROR_MESSAGES = {
  emptyCardNumber: {
    id: 'CheckoutPage.StepPayment.CreditCardForm.Error.emptyCardNumber',
  }
};

function MyComponent() {
  const paymentInputs = usePaymentInputs({  errorMessages: ERROR_MESSAGES });

  ...

  return <Whatever />;
}

Maybe it could be mentioned in the README, or maybe there's some way to handle it by the library itself, or maybe everyone who is more familiar with React hooks knows about it already ;)