Newer
Older
Nicolò Pretto
committed
import { useEffect, useState } from "react";
Phoomparin Mano
committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { loadStaticQuestion } from "embedding-sdk/lib/load-static-question";
import type { GenericErrorResponse } from "metabase/lib/errors";
import { defer } from "metabase/lib/promise";
import type Question from "metabase-lib/v1/Question";
import type { Card, Dataset } from "metabase-types/api";
type QuestionState = {
loading: boolean;
card: Card | null;
result: Dataset | null;
error: GenericErrorResponse | null;
};
export function useLoadStaticQuestion(
questionId: number | null,
parameterValues?: Record<string, string | number>,
) {
const [questionState, setQuestionState] = useState<QuestionState>({
loading: false,
card: null,
result: null,
error: null,
});
const updateQuestion = (newQuestion: Question) =>
setQuestionState(state => ({
...state,
card: newQuestion.card(),
loading: false,
error: null,
}));
useEffect(() => {
const cancelDeferred = defer();
async function loadCardData() {
setQuestionState(state => ({ ...state, loading: true }));
if (!questionId) {
return;
}
try {
const { card, result } = await loadStaticQuestion({
questionId,
parameterValues,
cancelDeferred,
});
setQuestionState({
card,
result,
loading: false,
error: null,
});
} catch (error) {
if (typeof error === "object") {
setQuestionState({
result: null,
card: null,
loading: false,
error,
});
} else {
console.error("error loading static question", error);
}
}
}
loadCardData();
return () => {
// cancel pending requests upon unmount
cancelDeferred.resolve();
};
}, [questionId, parameterValues]);
return { ...questionState, updateQuestion };
}