Skip to content

Commit e2775fd

Browse files
committed
feat: add custom hook and component that handles reordering
1 parent d16354e commit e2775fd

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

src/Reorder/Reorder.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import React from "react";
2+
3+
function Reorder({ index, reorderObj, children }) {
4+
return (
5+
<div
6+
draggable
7+
onDragStart={() => (reorderObj.onCardRef.current = index)}
8+
onDragEnter={() => (reorderObj.overCardRef.current = index)}
9+
onDragEnd={reorderObj.handleSwap}
10+
onDragOver={(e) => e.preventDefault()}
11+
>
12+
{children}
13+
</div>
14+
);
15+
}
16+
17+
export default Reorder;

src/Reorder/useReorder.js

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { useEffect, useRef, useState } from "react";
2+
3+
const useReorder = (items, setItems, sectionType) => {
4+
const onCardRef = useRef(0);
5+
const overCardRef = useRef(0);
6+
const timeoutRef = useRef(null);
7+
const latestItemsRef = useRef(items);
8+
const [response, setResponse] = useState(null);
9+
const [error, setError] = useState(null);
10+
11+
const handleSwap = () => {
12+
if (timeoutRef.current) {
13+
clearTimeout(timeoutRef.current);
14+
}
15+
16+
const updatedItems = [...items];
17+
const temp = updatedItems[onCardRef.current];
18+
updatedItems[onCardRef.current] = updatedItems[overCardRef.current];
19+
updatedItems[overCardRef.current] = temp;
20+
21+
setItems(updatedItems);
22+
23+
timeoutRef.current = setTimeout(() => {
24+
handleRequest(sectionType);
25+
}, 3000);
26+
};
27+
28+
const handleRequest = async (sectionType) => {
29+
// sectionType must be a valid resume section, e.g. education, experience, skills
30+
31+
const baseURL = "http://localhost:5000/resume/";
32+
try {
33+
const response = await fetch(`${baseURL}${sectionType}`, {
34+
method: "PUT",
35+
headers: {
36+
"Content-Type": "application/json",
37+
},
38+
body: JSON.stringify({ data: latestItemsRef.current }),
39+
});
40+
41+
if (!response.ok)
42+
throw new Error(`HTTP error! Status: ${response.status}`);
43+
44+
const data = await response.json();
45+
setResponse(data);
46+
setError(null);
47+
} catch (error) {
48+
setError(error);
49+
console.error(error);
50+
}
51+
};
52+
53+
useEffect(() => {
54+
latestItemsRef.current = items;
55+
}, [items]);
56+
57+
return {
58+
response,
59+
error,
60+
reorderObj: { handleSwap, onCardRef, overCardRef },
61+
};
62+
};
63+
64+
export default useReorder;

0 commit comments

Comments
 (0)