Skip to content

Commit 8185269

Browse files
authored
Merge pull request #18 from 6ri4n/feat-reorder-section-items
feat: add reordering custom hook and component
2 parents 3ae358d + 6c1af0b commit 8185269

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-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

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

0 commit comments

Comments
 (0)