From 5f5ae50dc6f81ef2376f25960698322b00268e2e Mon Sep 17 00:00:00 2001 From: Justin Poehnelt Date: Tue, 2 Mar 2021 15:34:50 -0700 Subject: [PATCH] feat: add callback (#10) --- src/index.test.tsx | 20 ++++++++++++++++++++ src/index.tsx | 23 ++++++++++++++++++++--- 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/src/index.test.tsx b/src/index.test.tsx index 970cb994..2c911c62 100644 --- a/src/index.test.tsx +++ b/src/index.test.tsx @@ -138,3 +138,23 @@ test("it should pass props to Loader and use the correct script url", () => { // compare url to what is generated directly from loader expect(script.src).toBe(new Loader(loaderOptions).createUrl()); }); + +test("it should execute the callback", async () => { + const callback = jest.fn(); + const loaderOptions: LoaderOptions = { + apiKey: "YOUR_API_KEY", + }; + + render(); + + expect(callback.mock.calls[0][0]).toBe(Status.LOADING) + expect(callback.mock.calls[0][1]).toBeInstanceOf(Loader) + + await executeLoaderCallback(); + + expect(callback.mock.calls[1][0]).toBe(Status.SUCCESS) + expect(callback.mock.calls[1][1]).toBeInstanceOf(Loader) + + expect(callback).toBeCalledTimes(2) + +}); diff --git a/src/index.tsx b/src/index.tsx index e39db82d..25763b81 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -32,6 +32,12 @@ export interface WrapperProps extends LoaderOptions { * Render prop used to switch on the status. */ render?: (status: Status) => ReactElement; + /** + * Callback prop used to access `@googlemaps/js-api-loader` and `Status`. + * + * Note: The callback be executed multiple times in the lifecycle of the component. + */ + callback?: (status: Status, loader: Loader) => void; } /** @@ -52,15 +58,26 @@ export interface WrapperProps extends LoaderOptions { export const Wrapper = ({ children, render, + callback, ...options }: WrapperProps): ReactElement => { const [status, setStatus] = useState(Status.LOADING); useEffect(() => { - new Loader(options).load().then( - () => setStatus(Status.SUCCESS), - () => setStatus(Status.FAILURE) + const loader = new Loader(options); + + const setStatusAndExecuteCallback = (status: Status) => { + if (callback) callback(status, loader); + setStatus(status); + }; + + setStatusAndExecuteCallback(Status.LOADING); + + loader.load().then( + () => setStatusAndExecuteCallback(Status.SUCCESS), + () => setStatusAndExecuteCallback(Status.FAILURE) ); + }, []); if (status === Status.SUCCESS && children) return <>{children};