Skip to content

Commit

Permalink
LPS-112034 Create FrameContext
Browse files Browse the repository at this point in the history
  • Loading branch information
p2kmgcl authored and brianchandotcom committed Apr 22, 2020
1 parent cc89220 commit cc2213a
Showing 1 changed file with 35 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,37 @@
*/

import {useIsMounted} from 'frontend-js-react-web';
import React, {useEffect, useState} from 'react';
import React, {useCallback, useContext, useEffect, useState} from 'react';
import {createPortal} from 'react-dom';

export default function Frame({children}) {
const [iframe, setIframe] = useState();
const [iframeBody, setIframeBody] = useState();
const setFrameContext = useSetFrameContext();
const isMounted = useIsMounted();

useEffect(() => {
let intervalId = null;

if (iframe) {
let body;
let _body;

intervalId = setInterval(() => {
if (isMounted() && body !== iframe.contentDocument.body) {
body = iframe.contentDocument.body;
setIframeBody(body);
if (isMounted()) {
if (_body !== iframe.contentDocument.body) {
setFrameContext(iframe.contentWindow);
setIframeBody(iframe.contentDocument.body);

_body = iframe.contentDocument.body;
}
}
}, 500);
}

return () => {
clearInterval(intervalId);
};
}, [iframe, isMounted]);
}, [iframe, isMounted, setFrameContext]);

return (
<>
Expand All @@ -47,3 +52,27 @@ export default function Frame({children}) {
</>
);
}

const FrameContext = React.createContext({
getValue: () => {},
setValue: () => {},
});

export function FrameContextProvider({children}) {
const [value, setValue] = useState(null);
const getValue = useCallback(() => value, [value]);

return (
<FrameContext.Provider value={{getValue, setValue}}>
{children}
</FrameContext.Provider>
);
}

export function useFrameContext() {
return useContext(FrameContext).getValue();
}

export function useSetFrameContext() {
return useContext(FrameContext).setValue;
}

0 comments on commit cc2213a

Please sign in to comment.