umami/hooks/useReport.js

77 lines
1.5 KiB
JavaScript
Raw Normal View History

import { produce } from 'immer';
2023-05-20 18:02:08 +02:00
import { useCallback, useEffect, useState } from 'react';
import useApi from './useApi';
const baseParameters = {
name: 'Untitled',
description: '',
parameters: {},
};
2023-05-20 18:02:08 +02:00
export function useReport(reportId, defaultParameters) {
const [report, setReport] = useState(null);
const [isRunning, setIsRunning] = useState(false);
const { get, post } = useApi();
const loadReport = async id => {
const data = await get(`/reports/${id}`);
setReport(data);
};
const runReport = useCallback(
async parameters => {
setIsRunning(true);
2023-05-31 01:49:22 +02:00
const { type } = report;
const data = await post(`/reports/${type}`, parameters);
setReport(
produce(state => {
state.parameters = parameters;
state.data = data;
return state;
}),
);
setIsRunning(false);
},
[report],
);
const updateReport = useCallback(
async data => {
setReport(
produce(state => {
const { parameters, ...rest } = data;
if (parameters) {
state.parameters = { ...state.parameters, ...parameters };
}
for (const key in rest) {
state[key] = rest[key];
}
2023-05-20 18:02:08 +02:00
return state;
}),
);
},
[report],
);
2023-05-20 18:02:08 +02:00
useEffect(() => {
if (!reportId) {
setReport({ ...baseParameters, ...defaultParameters });
} else {
loadReport(reportId);
2023-05-20 18:02:08 +02:00
}
}, []);
return { report, runReport, updateReport, isRunning };
2023-05-20 18:02:08 +02:00
}
export default useReport;