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

71 lines
1.8 KiB
JavaScript
Raw Normal View History

import { useState, useRef } from 'react';
2022-04-26 05:25:03 +00:00
import { getProfile } from 'api/getProfile';
import { setProfileData } from 'api/setProfileData';
import { setProfileImage } from 'api/setProfileImage';
import { getProfileImageUrl } from 'api/getProfileImageUrl';
2022-04-24 02:49:27 +00:00
export function useProfileContext() {
const [state, setState] = useState({
2023-01-02 06:28:12 +00:00
identity: {},
imageUrl: null,
2022-04-24 02:49:27 +00:00
});
2022-04-24 07:27:28 +00:00
const access = useRef(null);
2023-01-02 06:28:12 +00:00
const curRevision = useRef(null);
const setRevision = useRef(null);
const syncing = useRef(false);
2022-04-24 02:49:27 +00:00
const updateState = (value) => {
setState((s) => ({ ...s, ...value }))
}
2023-01-02 06:28:12 +00:00
const sync = async () => {
if (!syncing.current) {
if (setRevision.current !== curRevision.current) {
syncing.current = true;
const revision = curRevision.current;
try {
const identity = await getProfile(access.current);
const imageUrl = identity.image ? getProfileImageUrl(access.current, revision) : null;
updateState({ identity, imageUrl });
setRevision.current = revision;
}
catch(err) {
console.log(err);
syncing.current = false;
return;
}
syncing.current = false;
sync();
2022-04-24 02:49:27 +00:00
}
}
}
const actions = {
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;
2023-01-02 06:28:12 +00:00
curRevision.current = null;
setRevision.current = null;
setState({ identity: {}, imageUrl: null });
2022-05-16 06:33:17 +00:00
},
2022-04-24 07:27:28 +00:00
setRevision: (rev) => {
2023-01-02 06:28:12 +00:00
curRevision.current = rev;
sync();
2022-04-24 02:49:27 +00:00
},
setProfileData: async (name, location, description) => {
2022-04-25 19:16:25 +00:00
await setProfileData(access.current, name, location, description);
2022-04-24 02:49:27 +00:00
},
setProfileImage: async (image) => {
2022-04-25 19:16:25 +00:00
await setProfileImage(access.current, image);
2022-04-24 02:49:27 +00:00
},
}
return { state, actions }
}