alexislepresle / gatsby-plugin-paypal

💰 Add a PayPal Smart Payment Buttons to your Gatsby website easily.
8 stars 4 forks source link

Pass value to amount #4

Open guanacone opened 3 years ago

guanacone commented 3 years ago

How can I pass a dynamic price to the button?

I have a form in my component that updates the quantity of ordered product and and useEffect hook that updates the orderTotal anytime the quantity changes. The updated orderTotal is not updated in the paypal button... My issue is probably not directly related to this plugin but rather to my general understanding of React and Gatsby...

const Cart = ({ isCartOpen, close }) => {
  const price = 29995;
  const [orderTotal, setOrderTotal] = useState(price);
  const [orderQuantity, setOrderQuantity] = useState(1);
  const data = useStaticQuery(graphql`
  {
      file(relativePath: {eq: "assets/images/laser-smart-projector-pico_3.webp"}) {
        childImageSharp {
          gatsbyImageData(aspectRatio: 1, placeholder: BLURRED)
        }
      }
    }
  `);
  const productPic = getImage(data.file);

  useEffect(() => {
    setOrderTotal(orderQuantity * price);
  }, [orderQuantity]);

  return (
    <StyledDiv isCartOpen={isCartOpen}>
      <button onClick={close}>
        <div className='closing'></div>
        <div className='closing'></div>
      </button>
      <div className='cart-content'>
        <Link to='/about' onClick={close}>
          <GatsbyImage image={productPic} alt='folded vze projector'/>
          VZE: Music Visualizer
        </Link>
        <form>
          <label htmlFor='quantity'>Ordered quantity:</label>
          <input
            type='number'
            name='quantity'
            id='quantity'
            value={orderQuantity}
            onChange={
              (e) => {
                setOrderQuantity(e.target.value);
              }}
            min={0}
            max={5}
            required/>
        </form>
        <p>your order total is {formatMoney(orderTotal)}</p>
      </div>
      <Paypal
        style={{
          shape: 'rect',
          color: 'blue',
          layout: 'horizontal',
          label: 'paypal',
        }}
        amount={orderTotal}
        currency='USD'
      />
    </StyledDiv>
  );
};

export default Cart;
guanacone commented 3 years ago

Ok, so the amount is not updating because the button is only created on first render.

  useEffect(() => {
    if (typeof window !== `undefined`) {
      window.paypal
        .Buttons({
          ...props,
          createOrder: (props.createOrder ? props.createOrder : createOrderPaypal),
          onApprove: (props.onApprove ? props.onApprove : onApprovePaypal),
          onError: (props.onError ? props.onError : onErrorPaypal),
        })
        .render('#paypal-button');
    }
  }, []);

Could you fix that?

lawrencejberry commented 3 years ago

+1 on this issue. As @guanacone said, you can't dynamically change the amount (or pass in any new props for that matter) as the PayPal button is only created on component mount due to the empty [] dependencies array. Unfortunately it's not as simple as just adding props to the dependencies array, since this would cause additional buttons to be rendered. We need to find some way to clean up the old PayPal button before re-creating it with the latest props, but I can't see anything of the sort in the PayPal Checkout button API. It's possible using the special PayPal React button might do the trick?

lawrencejberry commented 3 years ago

In the meantime, a very ugly workaround is to set the value as a key on the component, which forces the component to re-mount whenever the value changes:

<Paypal
    // change the key to force a remount of the component which is needed for it to pick up new props
    key={value}
    amount={value}
    style={{
      color: "blue",
    }}
/>
guanacone commented 3 years ago

I ended up using react-paypal-button-v2

nNevermore commented 3 years ago

Hello, I have also a problem with this solution, so I did it in this way

 useEffect(() => {
     window.paypal
       .Buttons({
         createOrder: (data, actions) => {
           return actions.order.create({
             purchase_units: [
               {
                 description: product.description,
                 amount: {
                   currency_code: 'PLN',
                   value: productPrice,
                 },
               },
             ],
             "application_context": {
                shipping_preference: "NO_SHIPPING"
            },

           });
         },
         onApprove: async (data, actions) => {
           const order = await actions.order.capture();
           setPaidFor(true);
           console.log(order);
         },
         onError: err => {
           setError(err);
           console.error(err);
         },
       })
       .render(
           paypalRef.current
       );
   }, [productDescription, productPrice]);

and: <div id="paypalDiv"ref={paypalRef} /> have a nice day!

alexislepresle commented 3 years ago

Hello everyone,

Sorry I don't have much time at the moment. I will try to make the necessary updates soon. If you find a solution, you can make a PR :)

Have a nice day :)