Skip to content

Commit

Permalink
Use context
Browse files Browse the repository at this point in the history
  • Loading branch information
alucas-nickel committed Apr 26, 2023
1 parent 68b900e commit 2566e42
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
5 changes: 5 additions & 0 deletions src/PaylineContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { createContext } from "react";

const PaylineContext = createContext<{isLoaded: boolean}>({isLoaded: false});

export default PaylineContext;
8 changes: 5 additions & 3 deletions src/PaylineProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { ReactNode, useLayoutEffect, useState } from 'react';
import PaylineContext from './PaylineContext';

const getBaseUrl = (production: boolean) =>
production ? 'https://payment.cdn.payline.com/cdn' : 'https://homologation-payment.cdn.payline.com/cdn'
Expand Down Expand Up @@ -26,7 +27,8 @@ interface PaylineProviderProps {
function PaylineProvider({ production = false, children }: PaylineProviderProps) {
// add script
const scriptUrl = getScriptUrl(production);
const [, setIsLoaded] = useState(window.Payline !== undefined);
const [isLoaded, setIsLoaded] = useState(window.Payline !== undefined);

useLayoutEffect(() => {
let script: HTMLScriptElement | null = document.querySelector(`script[src="${scriptUrl}"]`);
if (!script) {
Expand Down Expand Up @@ -56,7 +58,7 @@ function PaylineProvider({ production = false, children }: PaylineProviderProps)
}, [stylesheetUrl]);

// render children
return <>{children}</>;
}
return <PaylineContext.Provider value={{isLoaded}}>{children}</PaylineContext.Provider>;
};

export default PaylineProvider;
4 changes: 4 additions & 0 deletions src/usePayline.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { useContext } from "react";
import PaylineContext from "./PaylineContext";

// See https://docs.payline.com/display/DT/API+JavaScript for full documentation of Payline API
type PaylineApi = {
endToken: (
Expand Down Expand Up @@ -37,6 +40,7 @@ declare global {

const usePayline = () => {
if (typeof window === 'undefined') return undefined;
if (!useContext(PaylineContext).isLoaded) return undefined

if (!window.Payline)
throw new Error('window.Payline is unavailable. Check if PaylineProvider is rendered within the component tree.');
Expand Down

0 comments on commit 2566e42

Please sign in to comment.