2021-06-04 07:20:16 +00:00
|
|
|
|
2021-06-23 16:40:48 +00:00
|
|
|
import { useCallback, useEffect } from 'react';
|
2021-08-05 23:30:31 +00:00
|
|
|
import { useSelector } from 'react-redux';
|
2021-07-22 23:04:56 +00:00
|
|
|
|
|
|
|
import { database } from '../../common/database';
|
2021-08-05 23:30:31 +00:00
|
|
|
import { initializeSpaceFromTeam } from '../../sync/vcs/initialize-model-from';
|
2021-07-22 23:04:56 +00:00
|
|
|
import { VCS } from '../../sync/vcs/vcs';
|
2021-08-05 23:30:31 +00:00
|
|
|
import { selectIsLoggedIn } from '../redux/selectors';
|
2021-06-23 16:40:48 +00:00
|
|
|
import { useSafeState } from './use-safe-state';
|
2021-06-04 07:20:16 +00:00
|
|
|
|
|
|
|
export const useRemoteSpaces = (vcs?: VCS) => {
|
2021-06-23 16:40:48 +00:00
|
|
|
const [loading, setLoading] = useSafeState(false);
|
2021-08-05 23:30:31 +00:00
|
|
|
const isLoggedIn = useSelector(selectIsLoggedIn);
|
2021-06-04 07:20:16 +00:00
|
|
|
|
|
|
|
const refresh = useCallback(async () => {
|
2021-08-05 23:30:31 +00:00
|
|
|
if (vcs && isLoggedIn) {
|
2021-06-04 07:20:16 +00:00
|
|
|
setLoading(true);
|
|
|
|
|
|
|
|
const teams = await vcs.teams();
|
2021-08-05 23:30:31 +00:00
|
|
|
const spaces = await Promise.all(teams.map(initializeSpaceFromTeam));
|
2021-06-04 07:20:16 +00:00
|
|
|
await database.batchModifyDocs({ upsert: spaces });
|
|
|
|
|
|
|
|
setLoading(false);
|
|
|
|
}
|
2021-08-05 23:30:31 +00:00
|
|
|
}, [vcs, setLoading, isLoggedIn]);
|
2021-06-04 07:20:16 +00:00
|
|
|
|
2021-06-15 04:21:06 +00:00
|
|
|
// If the refresh callback changes, refresh
|
2021-06-04 07:20:16 +00:00
|
|
|
useEffect(() => {
|
|
|
|
(async () => { await refresh(); })();
|
|
|
|
}, [refresh]);
|
|
|
|
|
|
|
|
return { loading, refresh };
|
|
|
|
};
|