Skip to content

Commit

Permalink
feat: add callback (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
jpoehnelt authored Mar 2, 2021
1 parent d0cfd1c commit 5f5ae50
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 3 deletions.
20 changes: 20 additions & 0 deletions src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<Wrapper {...{...loaderOptions, callback}} />);

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)

});
23 changes: 20 additions & 3 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand All @@ -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}</>;
Expand Down

0 comments on commit 5f5ae50

Please sign in to comment.