-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathChunkCollection.jsx
More file actions
104 lines (96 loc) · 2.82 KB
/
ChunkCollection.jsx
File metadata and controls
104 lines (96 loc) · 2.82 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
97
98
99
100
101
102
103
104
// @ts-check
import React, { useEffect, useState, useContext } from "react";
import { ChunkCollectionContext } from "./ChunkCollectionContext";
import { getCachedData, storeCache, computeClassName } from "./utilities";
import axios from "axios";
import { EditmodeContext } from "./EditmodeContext";
export function ChunkCollection({
children,
className,
identifier,
limit = "",
tags = [],
itemClass = "",
contentKey = null,
}) {
const [chunks, setChunk] = useState([]);
const cacheId = identifier + limit + tags.join("");
// const { collection } = useCollectionData(["Featured Projects"]);
const { projectId } = useContext(EditmodeContext);
useEffect(() => {
// Get data from localStorage
const api = axios.create({
baseURL: "https://api2.editmode.com/",
headers: {
Accept: "application/json",
},
params: {
referrer: window.location.href,
},
});
const cachedChunk = getCachedData(cacheId);
if (cachedChunk) {
const data = JSON.parse(cachedChunk);
setChunk(data);
}
const urlParams = new URLSearchParams({
limit,
collection_identifier: identifier || contentKey,
project_id: projectId,
});
tags.forEach((tag) => urlParams.append("tags[]", tag));
api
.get(`chunks?${urlParams}`)
.then((res) => {
storeCache(cacheId, res.data.chunks);
if (!cachedChunk) setChunk(res.data.chunks);
})
.catch((error) => {
console.error(
`Something went wrong trying to retrieve chunk collection: ${error}. Have you provided the correct Editmode identifier as a prop to your ChunkCollection component instance?`
);
});
}, [identifier]);
if (!chunks?.length) {
return null;
}
const placeholderChunk = chunks.length
? { ...chunks[0], placeholder: true }
: {};
return (
<div
className={computeClassName(className, "chunks-collection-wrapper")}
data-chunk-cache-id={cacheId}
data-chunk-collection-identifier={identifier}
>
{chunks.map((chunk) => (
<ChunkCollectionContext.Provider key={chunk.identifier} value={chunk}>
<div
className={computeClassName(
itemClass,
"chunks-collection-item--wrapper"
)}
>
{children}
</div>
</ChunkCollectionContext.Provider>
))}
{chunks.length && (
<ChunkCollectionContext.Provider
key={chunks[0].identifier + "dummy"}
value={placeholderChunk}
>
<div
className={computeClassName(
itemClass,
"chunks-col-placeholder-wrapper chunks-hide"
)}
>
{children}
</div>
</ChunkCollectionContext.Provider>
)}
</div>
);
}
export default ChunkCollection;