-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathFetchFromIdInput.tsx
76 lines (67 loc) · 2.28 KB
/
FetchFromIdInput.tsx
1
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
import React, { useEffect, useState } from "react";
import styled from "styled-components";
import { useDebounce } from "react-use";
import { Field } from "@kleros/ui-components-library";
import { useDisputeTemplateFromId } from "hooks/queries/useDisputeTemplateFromId";
import { isUndefined } from "utils/isUndefined";
const Container = styled.div`
display: flex;
flex-direction: column;
margin-top: 24px;
margin-left: 24px;
`;
const StyledInput = styled(Field)``;
const StyledHeader = styled.h2`
margin-top: 24px;
`;
interface IFetchFromID {
setDisputeTemplateInput: (templateData: string) => void;
setDataMappingsInput: (dataMappings: string) => void;
defaultTemplateID: string;
}
const FetchFromIDInput: React.FC<IFetchFromID> = ({
setDisputeTemplateInput,
setDataMappingsInput,
defaultTemplateID = "",
}) => {
const [templateId, setTemplateId] = useState<string>("");
const [debouncedTemplateId, setDebouncedTemplateId] = useState<string>("");
useDebounce(
() => {
setDebouncedTemplateId(templateId);
},
1000,
[templateId]
);
useEffect(() => setTemplateId(defaultTemplateID), [defaultTemplateID]);
const { data: templateFromId, isLoading, error } = useDisputeTemplateFromId(debouncedTemplateId);
useEffect(() => {
const templateData = templateFromId?.disputeTemplate?.templateData;
const templateDataMappings = templateFromId?.disputeTemplate?.templateDataMappings;
if (!isUndefined(templateData)) setDisputeTemplateInput(tryPrettify(templateData));
if (!isUndefined(templateDataMappings)) setDataMappingsInput(tryPrettify(templateDataMappings));
if (error) {
console.error("Error fetching template:", error);
}
}, [templateFromId, error]);
return (
<Container>
<StyledHeader>Fetch dispute template from template ID</StyledHeader>
<StyledInput
value={templateId}
placeholder="Enter template Id"
message={isLoading ? "fetching ..." : ""}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setTemplateId(e.target.value)}
/>
</Container>
);
};
// will try to format else will be repaired in editor
const tryPrettify = (text: string) => {
try {
return JSON.stringify(JSON.parse(text), null, 2);
} catch {
return text;
}
};
export default FetchFromIDInput;