-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuseChunk.js
More file actions
70 lines (59 loc) · 2.02 KB
/
useChunk.js
File metadata and controls
70 lines (59 loc) · 2.02 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
// @ts-check
import { useContext, useEffect, useState, useMemo } from "react";
import { EditmodeContext } from "./EditmodeContext";
import { api, renderChunk, computeContentKey, getCachedData, storeCache } from './utils'
export function useChunk(defaultContent, { identifier, type, contentKey, tag }) {
const { projectId, defaultChunks } = useContext(EditmodeContext);
const [chunk, setChunk] = useState({
chunk_type: type || "single_line_text",
content: defaultContent || "",
content_key: contentKey
});
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]
);
}
const url = `chunks/${identifier || contentKey}?project_id=${projectId}`;
useEffect(() => {
let cachedChunk = getCachedData(cacheId)
let newChunk = cachedChunk ? JSON.parse(cachedChunk) : fallbackChunk
if (newChunk) setChunk(newChunk)
// Fetch new data
if (contentKey || identifier) {
api
.get(url)
.then((res) => {
storeCache(cacheId, res.data)
if (!cachedChunk) setChunk(res.data)
}) // Store chunk to localstorage
.catch((error) => {
if (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, tag, props)
},
content: chunk.content
};
}
}