Skip to content

Commit

Permalink
Use contexte
Browse files Browse the repository at this point in the history
  • Loading branch information
alucas-nickel committed Apr 23, 2023
1 parent b25c8d3 commit 6d4d016
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 2 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;
6 changes: 4 additions & 2 deletions src/PaylineProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import React, { useLayoutEffect, useState } from 'react';
import PaylineContext from './PaylineContext';

type PropsType = {
production?: boolean;
Expand All @@ -20,7 +21,8 @@ const PaylineProvider: React.ComponentType<PropsType> = ({ production = false, c

// add script
const scriptUrl = `${baseUrl}/scripts/widget-min.js`;
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 @@ -50,7 +52,7 @@ const PaylineProvider: React.ComponentType<PropsType> = ({ production = false, c
}, [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 6d4d016

Please sign in to comment.