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

65 lines
1.7 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 { 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({
2022-04-25 22:06:00 +00:00
init: false,
2022-04-24 02:49:27 +00:00
profile: {},
});
2022-04-24 07:27:28 +00:00
const access = useRef(null);
const revision = useRef(null);
2022-04-24 02:49:27 +00:00
const next = useRef(null);
const updateState = (value) => {
setState((s) => ({ ...s, ...value }))
}
2022-04-24 07:27:28 +00:00
const setProfile = async (rev) => {
2022-04-24 02:49:27 +00:00
if (next.current == null) {
2022-04-24 07:27:28 +00:00
if (revision.current != rev) {
let profile = await getProfile(access.current);
2022-04-25 22:06:00 +00:00
updateState({ init: true, profile });
2022-04-24 07:27:28 +00:00
revision.current = rev;
}
2022-04-24 02:49:27 +00:00
if (next.current != null) {
2022-04-24 07:27:28 +00:00
let r = next.current;
2022-04-24 02:49:27 +00:00
next.current = null;
2022-04-24 07:27:28 +00:00
setProfile(r);
2022-04-24 02:49:27 +00:00
}
}
else {
2022-04-24 07:27:28 +00:00
next.current = rev;
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-04-24 07:27:28 +00:00
setRevision: (rev) => {
setProfile(rev);
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
},
2022-04-28 22:24:49 +00:00
getProfile: () => {
const { name, handle, image, revision } = state.profile;
if (image == null || image == '') {
return { name, handle };
}
return { name, handle, imageUrl: getProfileImageUrl(access.current, revision) };
},
2022-04-24 07:27:28 +00:00
profileImageUrl: () => getProfileImageUrl(access.current, revision.current),
2022-04-24 02:49:27 +00:00
}
return { state, actions }
}