2022-04-24 02:49:27 +00:00
|
|
|
import { useEffect, useState, useRef } from 'react';
|
2022-04-26 05:25:03 +00:00
|
|
|
import { getGroups } from 'api/getGroups';
|
2022-04-24 02:49:27 +00:00
|
|
|
|
|
|
|
export function useGroupContext() {
|
|
|
|
const [state, setState] = useState({
|
2022-04-25 22:06:00 +00:00
|
|
|
init: false,
|
2022-04-24 05:47:00 +00:00
|
|
|
groups: new Map(),
|
2022-04-24 02:49:27 +00:00
|
|
|
});
|
2022-04-24 07:27:28 +00:00
|
|
|
const access = useRef(null);
|
|
|
|
const revision = useRef(null);
|
2022-04-24 05:47:00 +00:00
|
|
|
const groups = useRef(new Map());
|
2022-04-24 07:27:28 +00:00
|
|
|
const next = useRef(null);
|
2022-04-24 02:49:27 +00:00
|
|
|
|
|
|
|
const updateState = (value) => {
|
|
|
|
setState((s) => ({ ...s, ...value }))
|
|
|
|
}
|
|
|
|
|
2022-04-24 07:27:28 +00:00
|
|
|
const updateGroups = async () => {
|
|
|
|
let delta = await getGroups(access.current, revision.current);
|
|
|
|
for (let group of delta) {
|
|
|
|
if (group.data) {
|
|
|
|
groups.set(group.id, group);
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
groups.delete(group.id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const setGroups = async (rev) => {
|
2022-04-24 05:47:00 +00:00
|
|
|
if (next.current == null) {
|
2022-04-24 07:27:28 +00:00
|
|
|
if (revision.current != rev) {
|
|
|
|
await updateGroups();
|
2022-04-25 22:06:00 +00:00
|
|
|
updateState({ init: true, groups: groups.current });
|
2022-04-24 07:27:28 +00:00
|
|
|
revision.current = rev;
|
2022-04-24 05:47:00 +00:00
|
|
|
}
|
|
|
|
if (next.current != null) {
|
2022-04-24 07:27:28 +00:00
|
|
|
let r = next.current;
|
2022-04-24 05:47:00 +00:00
|
|
|
next.current = null;
|
2022-04-24 07:27:28 +00:00
|
|
|
setGroups(r);
|
2022-04-24 05:47:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
else {
|
2022-04-24 07:27:28 +00:00
|
|
|
next.current = rev;
|
2022-04-24 05:47:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-24 02:49:27 +00:00
|
|
|
const actions = {
|
|
|
|
setToken: async (token) => {
|
2022-04-24 07:27:28 +00:00
|
|
|
access.current = token;
|
2022-04-24 02:49:27 +00:00
|
|
|
},
|
2022-04-24 07:27:28 +00:00
|
|
|
setRevision: async (rev) => {
|
|
|
|
setGroups(rev);
|
2022-04-24 02:49:27 +00:00
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
return { state, actions }
|
|
|
|
}
|
|
|
|
|