databag/net/web/src/context/useGroupContext.hook.js

64 lines
1.4 KiB
JavaScript
Raw Normal View History

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) {
2022-06-08 08:25:41 +00:00
groups.current.set(group.id, group);
2022-04-24 07:27:28 +00:00
}
else {
2022-06-08 08:25:41 +00:00
groups.current.delete(group.id);
2022-04-24 07:27:28 +00:00
}
}
}
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 = {
2022-05-16 06:33:17 +00:00
setToken: (token) => {
2022-04-24 07:27:28 +00:00
access.current = token;
2022-04-24 02:49:27 +00:00
},
2022-05-16 06:33:17 +00:00
clearToken: () => {
access.current = null;
setState({ init: false });
},
2022-04-24 07:27:28 +00:00
setRevision: async (rev) => {
setGroups(rev);
2022-04-24 02:49:27 +00:00
},
}
return { state, actions }
}