-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathuseCollectionChunks.js
More file actions
49 lines (43 loc) · 1.34 KB
/
useCollectionChunks.js
File metadata and controls
49 lines (43 loc) · 1.34 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
import React, { useEffect, useState } from "react";
import { getCachedData, storeCache } from "./utilities";
import axios from "axios";
export function useCollectionChunks(identifier, limit = "", tags = []) {
const [chunks, setChunk] = useState([]);
const cacheId = identifier + limit + tags.join("");
useEffect(() => {
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,
});
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 && !chunks.length) {
return null;
}
return chunks;
}