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