import { useState, useRef, useContext } from 'react'; import { StoreContext } from 'context/StoreContext'; export function useCardContext() { const [state, setState] = useState({ }); const store = useContext(StoreContext); const session = useRef(null); const curRevision = useRef(null); const setRevision = useRef(null); const syncing = useRef(false); const updateState = (value) => { setState((s) => ({ ...s, ...value })) } const sync = async () => { if (!syncing.current && setRevision.current !== curRevision.current) { syncing.current = true; try { const revision = curRevision.current; const { server, appToken, guid } = session.current; // get and store updateState({ status }); setRevision.current = revision; } catch(err) { console.log(err); syncing.current = false; return; } syncing.current = false; sync(); } }; const actions = { setSession: async (access) => { const { guid, server, appToken } = access; // load const revision = await store.actions.getCardRevision(guid); // update setRevision.current = revision; curRevision.current = revision; session.current = access; }, clearSession: () => { session.current = {}; updateState({ account: null }); }, setRevision: (rev) => { curRevision.current = rev; sync(); }, } return { state, actions } }