UNPKG

use-google-sheets

Version:

### A React Hook wrapper library for google-sheets-mapper for getting data from Google Sheets API v4

86 lines (82 loc) 2.14 kB
import * as React from 'react'; import GoogleSheetsMapper from 'google-sheets-mapper'; const Status = { pending: "pending", success: "success", error: "error" }; const initialState = { status: Status.pending, error: null, data: [] }; function reducer(state, action) { switch(action.type){ case Status.pending: return { ...state, status: Status.pending, error: null }; case Status.success: return { status: Status.success, error: null, data: action.payload }; case Status.error: return { ...state, status: Status.error, error: action.payload }; default: return state; } } const useGoogleSheets = ({ apiKey, sheetId, sheetsOptions = [] })=>{ const [state, dispatch] = React.useReducer(reducer, initialState); const sheetsRef = React.useRef(sheetsOptions); React.useEffect(()=>{ sheetsRef.current = sheetsOptions; }, [ sheetsOptions ]); const fetchData = React.useCallback(async ()=>{ dispatch({ type: Status.pending }); try { const mappedData = await GoogleSheetsMapper.fetchGoogleSheetsData({ apiKey, sheetId, sheetsOptions: sheetsRef.current }); dispatch({ type: Status.success, payload: mappedData }); } catch (error) { dispatch({ type: Status.error, payload: error instanceof Error ? error : error }); } }, [ apiKey, sheetId ]); React.useEffect(()=>{ fetchData(); }, [ fetchData ]); return { status: state.status, loading: state.status === Status.pending, error: state.error, data: state.data, refetch: fetchData }; }; export { Status, useGoogleSheets as default };