mirror of
https://github.com/rgrgogu/new_starr.git
synced 2026-09-27 00:12:54 +08:00
80 lines
2.9 KiB
React
80 lines
2.9 KiB
React
/***********************************************************************************************************************************************************************
|
|
* File Name : GroupContext.jsx
|
|
* Type : Context / Provider
|
|
* Description : Client group context.
|
|
* Covers: fetching the current user's groups and a single group detail.
|
|
* Used by: GroupList.jsx
|
|
***********************************************************************************************************************************************************************/
|
|
import { createContext, useCallback, useContext, useState } from 'react';
|
|
import api from '@/utils/api.util';
|
|
import { toast } from 'sonner';
|
|
|
|
const BASE = '/client/groups';
|
|
|
|
const GroupContext = createContext(null);
|
|
|
|
export function useGroup() {
|
|
const ctx = useContext(GroupContext);
|
|
if (!ctx) throw new Error('useGroup must be used within a GroupProvider');
|
|
return ctx;
|
|
}
|
|
|
|
export function GroupProvider({ children }) {
|
|
const [groups, setGroups] = useState([]);
|
|
const [group, setGroup] = useState(null);
|
|
const [loading, setLoading] = useState(false);
|
|
|
|
const request = useCallback(async (fn) => {
|
|
setLoading(true);
|
|
try {
|
|
return await fn();
|
|
} catch (err) {
|
|
const message = err?.response?.data?.message ?? 'Something went wrong.';
|
|
toast(message, {
|
|
action: {
|
|
label: "Close",
|
|
onClick: () => {}
|
|
}
|
|
});
|
|
return null;
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
}, []);
|
|
|
|
// ─── GET MY GROUPS ────────────────────────────────────────────────────────
|
|
// GET /client/groups
|
|
const fetchGroups = useCallback(
|
|
() =>
|
|
request(async () => {
|
|
const res = await api.get(BASE);
|
|
const data = res.data?.data ?? [];
|
|
setGroups(data);
|
|
return data;
|
|
}),
|
|
[request]
|
|
);
|
|
|
|
// ─── GET ONE GROUP ────────────────────────────────────────────────────────
|
|
// GET /client/groups/:groupId
|
|
const fetchGroup = useCallback(
|
|
(groupId) =>
|
|
request(async () => {
|
|
const res = await api.get(`${BASE}/${groupId}`);
|
|
const data = res.data?.data ?? null;
|
|
setGroup(data);
|
|
return data;
|
|
}),
|
|
[request]
|
|
);
|
|
|
|
return (
|
|
<GroupContext.Provider value={{
|
|
groups, group,
|
|
loading,
|
|
fetchGroups, fetchGroup,
|
|
}}>
|
|
{children}
|
|
</GroupContext.Provider>
|
|
);
|
|
} |