64 lines
2.0 KiB
React
64 lines
2.0 KiB
React
/*
|
|
Copyright (C) 2025 QuantumNous
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
it under the terms of the GNU Affero General Public License as
|
|
published by the Free Software Foundation, either version 3 of the
|
|
License, or (at your option) any later version.
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
GNU Affero General Public License for more details.
|
|
|
|
You should have received a copy of the GNU Affero General Public License
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
For commercial licensing, please contact support@quantumnous.com
|
|
*/
|
|
import React, { createContext, useReducer, useCallback } from 'react';
|
|
import { reducer, initialState } from './reducer';
|
|
import { API } from '../../helpers/api';
|
|
|
|
export const OrgContext = createContext([initialState, () => {}]);
|
|
|
|
export const OrgProvider = ({ children }) => {
|
|
const [state, dispatch] = useReducer(reducer, initialState);
|
|
|
|
const fetchOrgs = useCallback(async () => {
|
|
dispatch({ type: 'set_loading', payload: true });
|
|
try {
|
|
const res = await API.get('/api/org/list');
|
|
if (res.data.success) {
|
|
dispatch({ type: 'set_orgs', payload: res.data.data || [] });
|
|
}
|
|
} catch {
|
|
// ignore
|
|
} finally {
|
|
dispatch({ type: 'set_loading', payload: false });
|
|
}
|
|
}, []);
|
|
|
|
const setCurrentOrg = useCallback((org, role) => {
|
|
dispatch({ type: 'set_current_org', payload: { org, role } });
|
|
if (org) {
|
|
localStorage.setItem('current_org_id', String(org.id));
|
|
} else {
|
|
localStorage.removeItem('current_org_id');
|
|
}
|
|
}, []);
|
|
|
|
const clearOrg = useCallback(() => {
|
|
dispatch({ type: 'clear' });
|
|
localStorage.removeItem('current_org_id');
|
|
}, []);
|
|
|
|
return (
|
|
<OrgContext.Provider
|
|
value={[state, dispatch, { fetchOrgs, setCurrentOrg, clearOrg }]}
|
|
>
|
|
{children}
|
|
</OrgContext.Provider>
|
|
);
|
|
};
|