인터넷에 돌아다니는 google-spreadsheet나 gapi-script 라이브러리를 사용하지 않고 구현하는 방법을 적을 예정임
gapi-script를 사용하다가 어느 순간부터 불러오기가 안 됨(init 에러)
깃이슈를 찾아보니 라이브러리 지원 중단된 모양..
리액트를 사용해서 개발한 사람들 중 google-spreadsheet 라이브러리를 사용하는 사람을 발견
하지만 이것도 언젠간 라이브러리 중단이 될까 미리 걱정해서 REST API로 구현하려고 했지만 OAuth 오류가 발생해서 그냥 JSON으로 데이터를 가져오는 것은 쉽게 됬지만 시트를 추가한다던지 그런 것은 불가능했음
그래서 결국 찾은 것이 script 태그로 공식 구글 시트 api에서 제공하는 링크를 불러오기로 결정
추가해야할 url은 두 가지임
1번은 gapi를, 2번은 google을 불러올 수 있음
나는 2번 링크가 코드가 짧길래 2번으로 활용
import { useState, useEffect } from 'react';
export const useScript = (src) => {
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
let script = document.querySelector(`script[src="${src}"]`);
if (!script) {
script = document.createElement('script');
script.src = src;
script.async = true;
script.defer = true;
}
const handleLoad = () => setLoading(true);
const handleError = (e) => setError(e);
script.addEventListener('load', handleLoad);
script.addEventListener('error', handleError);
document.body.appendChild(script);
return () => {
script.removeEventListener('load', handleLoad);
script.removeEventListener('error', handleError);
};
}, [src]);
return [loading, error];
};
loading1과 loading2가 모두 호출이 되어야만 gapi와 google을 불러올 수 있기 때문에 둘이 호출된 후 oauth를 초기화하고 gapi를 load함
export const GoogleInit = () => {
const [loading1] = useScript('https://apis.google.com/js/api.js');
const [loading2] = useScript('https://accounts.google.com/gsi/client');
const promise = new Promise((resolve, reject) => {
const initClient = async () => {
await window.gapi.client
.init({
apiKey: credentials.API_KEY,
discoveryDocs: [
'https://sheets.googleapis.com/$discovery/rest?version=v4',
],
})
.then(() => {
console.log('성공');
resolve(true);
})
.catch(() => {
console.log('실패');
reject(false);
});
};
if (loading1 && loading2) {
window.google.accounts.oauth2.initTokenClient({
client_id: credentials.client_id,
scope: SCOPE,
});
window.gapi.load('client:auth2', initClient);
}
});
return promise;
};
이걸로 진심 일주일 넘게 머가리 빡빡쳐가면서 구글링 함..
진짜 리액트 지원해주는 라이브러리 공식으로 만들어줘라...