Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useCartElement and useCartElementState hooks #335

Merged
merged 4 commits into from
Oct 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .storybook/example.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ const addDemo = (directory, file, stories) => {

const hooksStories = storiesOf('react-stripe-js/Hooks', module);
require
.context('../examples/hooks/', false, /\/\d-(.*).js$/)
.context('../examples/hooks/', false, /\/\d+-(.*).js$/)
.keys()
.forEach((key) => {
addDemo('hooks', key.slice(2), hooksStories);
});

const classStories = storiesOf('react-stripe-js/Class Components', module);
require
.context('../examples/class-components/', false, /\/\d-(.*).js$/)
.context('../examples/class-components/', false, /\/\d+-(.*).js$/)
.keys()
.forEach((key) => {
addDemo('class-components', key.slice(2), classStories);
Expand Down
155 changes: 155 additions & 0 deletions examples/hooks/10-Cart.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
// This example shows you how to set up React Stripe.js and use Elements.
// Learn how to use the Cart Element to store your customers purchases using the official Stripe docs.
// https://stripe.com/docs/elements/cart-element

import React from 'react';
import {loadStripe} from '@stripe/stripe-js';
import {
CartElement,
Elements,
useCartElement,
useCartElementState,
} from '../../src';

import '../styles/common.css';

const ProductPage = ({options, productId}) => {
const cartElement = useCartElement();
const cartElementState = useCartElementState();

const handleCheckout = async () => {
if (!cartElement) return;
// Redirect to Checkout page
cartElement.cancelCheckout('Error message here');
};

const handleLineItemClick = async (event) => {
if (!cartElement) return;
// Block native link redirect
event.preventDefault();
console.log(event.url);
};

const handleShow = () => {
if (!cartElement) return;
cartElement.show();
};

const handleAddLineItem = () => {
if (!cartElement) return;
cartElement.addLineItem({product: productId});
};

return (
<div>
<button type="button" onClick={handleAddLineItem}>
Add line item
</button>
<button type="button" onClick={handleShow}>
View cart ({cartElementState?.lineItems?.count || 0})
</button>
<CartElement
options={options}
onCheckout={handleCheckout}
onLineItemClick={handleLineItemClick}
/>
</div>
);
};

const THEMES = ['stripe', 'flat', 'none'];

const App = () => {
const [pk, setPK] = React.useState(
window.sessionStorage.getItem('react-stripe-js-pk') || ''
);
const [clientSecret, setClientSecret] = React.useState(
window.sessionStorage.getItem('react-stripe-js-client-secret') || ''
);
const [productId, setProductId] = React.useState(
window.sessionStorage.getItem('react-stripe-js-product-id') || ''
);

React.useEffect(() => {
window.sessionStorage.setItem('react-stripe-js-pk', pk || '');
}, [pk]);

React.useEffect(() => {
window.sessionStorage.setItem(
'react-stripe-js-client-secret',
clientSecret || ''
);
}, [clientSecret]);

React.useEffect(() => {
window.sessionStorage.setItem(
'react-stripe-js-product-id',
productId || ''
);
}, [productId]);

const [stripePromise, setStripePromise] = React.useState();
const [theme, setTheme] = React.useState('stripe');

const handleSubmit = (e) => {
e.preventDefault();
setStripePromise(loadStripe(pk, {betas: ['cart_beta_1']}));
};

const handleThemeChange = (e) => {
setTheme(e.target.value);
};

const handleUnload = () => {
setStripePromise(null);
setClientSecret(null);
};

return (
<>
<form onSubmit={handleSubmit}>
<label>
Publishable key{' '}
<input value={pk} onChange={(e) => setPK(e.target.value)} />
</label>
<label>
Cart Session client_secret
<input
value={clientSecret}
onChange={(e) => setClientSecret(e.target.value)}
/>
</label>
<label>
Product ID{' '}
<input
value={productId}
onChange={(e) => setProductId(e.target.value)}
/>
</label>
<button style={{marginRight: 10}} type="submit">
Load
</button>
<button type="button" onClick={handleUnload}>
Unload
</button>
<label>
Theme
<select onChange={handleThemeChange}>
{THEMES.map((val) => (
<option key={val} value={val}>
{val}
</option>
))}
</select>
</label>
</form>
{stripePromise && clientSecret && (
<Elements stripe={stripePromise} options={{appearance: {theme}}}>
<ProductPage options={{clientSecret}} productId={productId} />
</Elements>
)}
</>
);
};

export default App;
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@
"@babel/preset-env": "^7.7.1",
"@babel/preset-react": "^7.7.0",
"@storybook/react": "^6.5.0-beta.8",
"@stripe/stripe-js": "^1.38.1",
"@stripe/stripe-js": "^1.42.0",
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.1.1",
"@testing-library/react-hooks": "^8.0.0",
Expand Down Expand Up @@ -106,7 +106,7 @@
"@types/react": "18.0.5"
},
"peerDependencies": {
"@stripe/stripe-js": "^1.41.0",
"@stripe/stripe-js": "^1.42.0",
"react": "^16.8.0 || ^17.0.0 || ^18.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
}
Expand Down
25 changes: 24 additions & 1 deletion src/components/Elements.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,14 @@ import React, {StrictMode} from 'react';
import {render, act} from '@testing-library/react';
import {renderHook} from '@testing-library/react-hooks';

import {Elements, useElements, useStripe, ElementsConsumer} from './Elements';
import {
Elements,
useElements,
useStripe,
ElementsConsumer,
useCartElement,
useCartElementState,
} from './Elements';
import * as mocks from '../../test/mocks';

describe('Elements', () => {
Expand Down Expand Up @@ -293,6 +300,22 @@ describe('Elements', () => {
);
});

test('throws when trying to call useCartElement outside of Elements context', () => {
const {result} = renderHook(() => useCartElement());

expect(result.error && result.error.message).toBe(
'Could not find Elements context; You need to wrap the part of your app that calls useCartElement() in an <Elements> provider.'
);
});

test('throws when trying to call useCartElementState outside of Elements context', () => {
const {result} = renderHook(() => useCartElementState());

expect(result.error && result.error.message).toBe(
'Could not find Elements context; You need to wrap the part of your app that calls useCartElementState() in an <Elements> provider.'
);
});

describe('React.StrictMode', () => {
test('creates elements twice in StrictMode', () => {
const TestComponent = () => {
Expand Down
68 changes: 67 additions & 1 deletion src/components/Elements.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,33 @@ export const parseElementsContext = (
return ctx;
};

interface CartElementContextValue {
cart: stripeJs.StripeCartElement | null;
cartState: stripeJs.StripeCartElementPayloadEvent | null;
setCart: (cart: stripeJs.StripeCartElement | null) => void;
setCartState: (
cartState: stripeJs.StripeCartElementPayloadEvent | null
) => void;
}

const CartElementContext = React.createContext<CartElementContextValue | null>(
null
);
CartElementContext.displayName = 'CartElementContext';

export const parseCartElementContext = (
ctx: CartElementContextValue | null,
useCase: string
): CartElementContextValue => {
if (!ctx) {
throw new Error(
`Could not find Elements context; You need to wrap the part of your app that ${useCase} in an <Elements> provider.`
);
}

return ctx;
};

interface ElementsProps {
/**
* A [Stripe object](https://stripe.com/docs/js/initializing) or a `Promise` resolving to a `Stripe` object.
Expand Down Expand Up @@ -116,6 +143,14 @@ export const Elements: FunctionComponent<PropsWithChildren<ElementsProps>> = (({
rawStripeProp,
]);

const [cart, setCart] = React.useState<stripeJs.StripeCartElement | null>(
null
);
const [
cartState,
setCartState,
] = React.useState<stripeJs.StripeCartElementPayloadEvent | null>(null);

// For a sync stripe instance, initialize into context
const [ctx, setContext] = React.useState<ElementsContextValue>(() => ({
stripe: parsed.tag === 'sync' ? parsed.stripe : null,
Expand Down Expand Up @@ -205,7 +240,13 @@ export const Elements: FunctionComponent<PropsWithChildren<ElementsProps>> = (({
}, [ctx.stripe]);

return (
<ElementsContext.Provider value={ctx}>{children}</ElementsContext.Provider>
<ElementsContext.Provider value={ctx}>
<CartElementContext.Provider
value={{cart, setCart, cartState, setCartState}}
>
{children}
</CartElementContext.Provider>
</ElementsContext.Provider>
);
}) as FunctionComponent<PropsWithChildren<ElementsProps>>;

Expand All @@ -221,6 +262,13 @@ export const useElementsContextWithUseCase = (
return parseElementsContext(ctx, useCaseMessage);
};

export const useCartElementContextWithUseCase = (
useCaseMessage: string
): CartElementContextValue => {
const ctx = React.useContext(CartElementContext);
return parseCartElementContext(ctx, useCaseMessage);
};

/**
* @docs https://stripe.com/docs/stripe-js/react#useelements-hook
*/
Expand All @@ -237,6 +285,24 @@ export const useStripe = (): stripeJs.Stripe | null => {
return stripe;
};

/**
* @docs https://stripe.com/docs/payments/checkout/cart-element
*/
export const useCartElement = (): stripeJs.StripeCartElement | null => {
const {cart} = useCartElementContextWithUseCase('calls useCartElement()');
return cart;
};

/**
* @docs https://stripe.com/docs/payments/checkout/cart-element
*/
export const useCartElementState = (): stripeJs.StripeCartElementPayloadEvent | null => {
const {cartState} = useCartElementContextWithUseCase(
'calls useCartElementState()'
);
return cartState;
};

interface ElementsConsumerProps {
children: (props: ElementsContextValue) => ReactNode;
}
Expand Down
Loading