-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuseChunk.js
More file actions
96 lines (84 loc) · 2.43 KB
/
useChunk.js
File metadata and controls
96 lines (84 loc) · 2.43 KB
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// @ts-check
import { useContext, useEffect, useState, useMemo } from "react";
import axios from "axios";
import { EditmodeContext } from "./EditmodeContext";
import {
renderChunk,
computeContentKey,
getCachedData,
storeCache,
} from "./utilities";
export function useChunk(defaultContent, { identifier, type, contentKey }) {
const { projectId, defaultChunks } = useContext(EditmodeContext);
const [chunk, setChunk] = useState(undefined);
if (!contentKey) {
contentKey = defaultContent ? computeContentKey(defaultContent) : null;
}
const cacheId = identifier || contentKey + projectId;
let fallbackChunk;
if (typeof defaultChunks !== "undefined") {
fallbackChunk = useMemo(() => {
if (identifier) {
return defaultChunks.find(
(chunkItem) => chunkItem.identifier === identifier
);
} else {
return defaultChunks.find(
(chunkItem) =>
chunkItem.content_key === contentKey &&
chunkItem.project_id == projectId
);
}
}, [defaultChunks, identifier]);
}
let url = `chunks/${identifier || contentKey}?project_id=${projectId}`;
useEffect(() => {
// Render content
const api = axios.create({
baseURL: "https://api2.editmode.com/",
headers: {
Accept: "application/json",
},
params: {
referrer: window.location.href,
},
});
let cachedChunk = getCachedData(cacheId);
let newChunk = cachedChunk
? JSON.parse(cachedChunk)
: fallbackChunk || {
chunk_type: type || "single_line_text",
content: defaultContent,
content_key: contentKey,
};
if (newChunk) setChunk(newChunk);
// Fetch new data
let error;
api
.get(url)
.then((res) => {
storeCache(cacheId, res.data);
if (!cachedChunk) setChunk(res.data);
}) // Store chunk to localstorage
.catch((error) => console.log(error)); // Set error state
if (error && identifier) {
console.warn(
`Something went wrong trying to retrieve chunk data: ${error}. Have you provided the correct Editmode identifier (${identifier}) as a prop to your Chunk component instance?`
);
}
}, [cacheId]);
if (chunk) {
return {
Component(props) {
return renderChunk(chunk, props);
},
content: chunk.content,
};
} else {
return {
Component() {
return null;
},
};
}
}