Skip to content

Commit

Permalink
Merge pull request #372 from NUS-Project-SaBai/hooks/save-on-write
Browse files Browse the repository at this point in the history
Hooks: Save On Write
  • Loading branch information
AngPengXuan authored Dec 13, 2024
2 parents 5a107b4 + 4986360 commit 54f34fd
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 53 deletions.
2 changes: 1 addition & 1 deletion components/SideMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { VillageContext } from '@/context/VillageContext';
import axiosInstance from '@/pages/api/_axiosInstance';

// Version number here
const version = 'v2024.12.12 11AM';
const version = 'v2024.12.13 1PM';

const navigation = [
{
Expand Down
44 changes: 44 additions & 0 deletions hooks/useSaveOnWrite.js
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];
}
63 changes: 13 additions & 50 deletions pages/records/patient-consultation/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import axiosInstance from '@/pages/api/_axiosInstance';
import CustomModal from '@/components/CustomModal';
import useWithLoading from '@/utils/loading';
import NoVisitPlaceholder from '@/components/records/NoVisitPlaceholder';
import useSaveOnWrite from '@/hooks/useSaveOnWrite';

const PatientConsultation = () => {
const [mounted, setMounted] = useState(false);
Expand All @@ -37,7 +38,11 @@ const PatientConsultation = () => {
const [consultationModalOpen, setConsultationModalOpen] = useState(false);

// Order Form Modal hooks
const [orders, setOrders] = useState([]);
const [orders, setOrders, clearOrdersStorageData] = useSaveOnWrite(
'orders',
[],
[selectedVisitID]
);
const blankOrderFormDetails = {
quantity: '',
medicine: 0, // refers to the medcine id
Expand All @@ -49,59 +54,16 @@ const PatientConsultation = () => {
const [orderFormModalOpen, setOrderFormModalOpen] = useState(false);

// Consultation Form hooks
const [consultationFormDetails, setConsultationFormDetails] = useState({
diagnoses: [],
});
const [
consultationFormDetails,
setConsultationFormDetails,
clearConsultStorageData,
] = useSaveOnWrite('consult', { diagnoses: [] }, [selectedVisitID]);

useEffect(() => {
onRefresh();
}, []);

// Load saved data from localStorage when the component mounts
useEffect(() => {
const savedConsultData = localStorage.getItem(
`consultationFormDetails_visit${selectedVisitID}`
);
if (savedConsultData) {
setConsultationFormDetails(JSON.parse(savedConsultData));
}
const savedOrderData = localStorage.getItem(
`orders_visit${selectedVisitID}`
);
if (savedOrderData) {
setOrders(JSON.parse(savedOrderData));
}
}, [selectedVisitID]);
// Save consultation form data to localStorage whenever it changes
useEffect(() => {
const timeout = setTimeout(() => {
localStorage.setItem(
`consultationFormDetails_visit${selectedVisitID}`,
JSON.stringify(consultationFormDetails)
);
}, 500);
return () => clearTimeout(timeout);
}, [selectedVisitID, consultationFormDetails]);
// Save orders form data to localStorage whenever it changes
useEffect(() => {
const timeout = setTimeout(() => {
localStorage.setItem(
`orders_visit${selectedVisitID}`,
JSON.stringify(orders)
);
}, 500);
return () => clearTimeout(timeout);
}, [selectedVisitID, orders]);
// Purge data from localStorage on successful submit
const clearLocalStorageData = () => {
localStorage.removeItem(`consultationFormDetails_visit${selectedVisitID}`);
localStorage.removeItem(`orders_visit${selectedVisitID}`);
setConsultationFormDetails({
diagnoses: [],
});
setOrders([]);
};

const onRefresh = useWithLoading(async () => {
const patientID = Router.query.id;
try {
Expand Down Expand Up @@ -223,7 +185,8 @@ const PatientConsultation = () => {
};

await axiosInstance.post('/consults', combinedPayload);
clearLocalStorageData();
clearOrdersStorageData();
clearConsultStorageData();

toast.success('Medical Consult Completed!');
Router.push('/records');
Expand Down
8 changes: 6 additions & 2 deletions pages/registration/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import CustomModal from '@/components/CustomModal';
import { PageTitle } from '@/components/TextComponents';
import { REGISTRATION_FORM_FIELDS } from '@/utils/constants';
import { VillageContext } from '@/context/VillageContext';
import useSaveOnWrite from '@/hooks/useSaveOnWrite';

export const submitNewVisit = async patient => {
try {
Expand All @@ -40,13 +41,15 @@ const Registration = () => {

const [patientModalOpen, setPatientModalOpen] = useState(false);

const [imageDetails, setImageDetails] = useState(null);
const [imageDetails, setImageDetails, clearImageDetailsLocalStorage] =
useSaveOnWrite('image', null);

const [scanModalOpen, setScanModalOpen] = useState(false);

const [scanSuggestionsList, setScanSuggestionsList] = useState([]);

const [formDetails, setFormDetails] = useState(REGISTRATION_FORM_FIELDS);
const [formDetails, setFormDetails, clearFormDetailsLocalStorage] =
useSaveOnWrite('registration', REGISTRATION_FORM_FIELDS);

const { village } = useContext(VillageContext);

Expand Down Expand Up @@ -161,6 +164,7 @@ const Registration = () => {
village_prefix: 'SV',
}));
setImageDetails(null);
clearFormDetailsLocalStorage();
toast.success('New patient created!');
onRefresh();

Expand Down

0 comments on commit 54f34fd

Please sign in to comment.