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

73 lines
1.9 KiB
JavaScript
Raw Normal View History

import { useState, useRef } from 'react';
2023-01-02 23:20:58 +00:00
import { getUsername } from 'api/getUsername';
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 () => {
2023-01-02 22:59:27 +00:00
if (!syncing.current && setRevision.current !== curRevision.current) {
syncing.current = true;
2023-01-02 06:28:12 +00:00
2023-01-02 22:59:27 +00:00
try {
const revision = curRevision.current;
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);
2023-01-02 06:28:12 +00:00
syncing.current = false;
2023-01-02 22:59:27 +00:00
return;
2022-04-24 02:49:27 +00:00
}
2023-01-02 22:59:27 +00:00
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
},
2023-01-02 22:59:27 +00:00
getHandleStatus: async (name) => {
return await getUsername(name, access.current);
},
2022-04-24 02:49:27 +00:00
}
return { state, actions }
}