react-gapi
Version:
Google API per React hook
31 lines (28 loc) • 973 B
JavaScript
import { useContext, useState, useRef, useEffect } from 'react';
import { GoogleApiContext } from './GoogleApiContext.js';
function useGoogleApi(options = {}) {
const { gapi , configure } = useContext(GoogleApiContext) ?? {};
const [configureState, setConfigureState] = useState();
const mounted = useRef(true);
useEffect(()=>{
mounted.current = true;
return ()=>{
mounted.current = false;
};
});
const [, rerender] = useState();
const auth = gapi?.auth2?.getAuthInstance();
useEffect(()=>{
if (auth) {
auth.isSignedIn.listen(()=>mounted.current && rerender({})
);
auth.currentUser.listen(()=>mounted.current && rerender({})
);
}
}, [
auth
]);
return configure ? configure(options, (newState)=>mounted.current && newState !== configureState && setConfigureState(newState)
) : undefined;
}
export { useGoogleApi };