Skip to content

Instantly share code, notes, and snippets.

@mizchi
Last active September 8, 2019 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizchi/7572ff6ee77aadbbf569e16ec1f897ef to your computer and use it in GitHub Desktop.
Save mizchi/7572ff6ee77aadbbf569e16ec1f897ef to your computer and use it in GitHub Desktop.
import React, { useEffect, useState, useCallback } from "react";
let _installPrompt: any;
window.addEventListener("beforeinstallprompt", e => {
e.preventDefault();
_installPrompt = e;
});
function AppInstallButton() {
const [prompt, setInstallPrompt] = useState<any>(_installPrompt);
useEffect(() => {
if (_installPrompt) return;
const id = setInterval(() => {
if (_installPrompt) {
setInstallPrompt(_installPrompt);
if (id) clearInterval(id);
}
}, 3000);
return () => clearInterval(id);
}, []);
const onClickInstall = useCallback(() => {
if (prompt) {
prompt.prompt();
}
}, [prompt]);
return (
<button disabled={!prompt} onClick={onClickInstall}>
Install
</button>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment