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

55 lines
1.1 KiB
JavaScript
Raw Normal View History

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