-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #372 from NUS-Project-SaBai/hooks/save-on-write
Hooks: Save On Write
- Loading branch information
Showing
4 changed files
with
64 additions
and
53 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import { useState, useEffect } from 'react'; | ||
|
||
export default function useSaveOnWrite( | ||
name, | ||
initialFormDetails, | ||
dependencies = [] | ||
) { | ||
const [formDetails, setFormDetails] = useState(initialFormDetails); | ||
|
||
// Generate the storage key dynamically based on dependencies | ||
const generateStorageKey = () => { | ||
const dependencyKey = dependencies | ||
.map((dep, index) => `dep${index + 1}=${dep}`) | ||
.join('_'); | ||
return `current_${name}_form_details_${dependencyKey}`; | ||
}; | ||
|
||
const storageKey = generateStorageKey(); | ||
|
||
// Load saved data from localStorage when the component mounts | ||
useEffect(() => { | ||
const savedData = localStorage.getItem(storageKey); | ||
if (savedData) { | ||
console.log(savedData); | ||
setFormDetails(JSON.parse(savedData)); | ||
} | ||
}, dependencies); | ||
|
||
// Save registration form data to localStorage whenever it changes | ||
useEffect(() => { | ||
const timeout = setTimeout(() => { | ||
localStorage.setItem(storageKey, JSON.stringify(formDetails)); | ||
}, 500); | ||
return () => clearTimeout(timeout); | ||
}, [...dependencies, formDetails]); | ||
|
||
// Purge data from localStorage on successful submit | ||
const clearLocalStorageData = () => { | ||
localStorage.removeItem(storageKey); | ||
setFormDetails(initialFormDetails); | ||
}; | ||
|
||
return [formDetails, setFormDetails, clearLocalStorageData]; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters