Skip to content

Commit

Permalink
seperated concerns with useOnlineState and the toasters (#56)
Browse files Browse the repository at this point in the history
  • Loading branch information
JurreBrandsenInfoSupport authored Mar 27, 2024
1 parent 6e908f1 commit cdd01cf
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 74 deletions.
93 changes: 30 additions & 63 deletions src/components/survey-questionnaire.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { type Session } from "next-auth";
import { slugify } from "~/utils/slugify";

import ProgressionBar from "./progression-bar";
import useScreenSize from "./useScreenSize";
import useScreenSize from "./use-screen-size";
import { MobileSurveyQuestionnaire } from "./mobile/survey-questions";
import { SurveyQuestions } from "./survey-questions";
import { MobileProgressionBar } from "./mobile/progression-bar";
Expand All @@ -28,6 +28,7 @@ import { useSubmission } from "~/utils/submission-utils";
import { SpinnerButton } from "./ui/button-spinner";
import { Form } from "./ui/form";
import renderNotFoundPage from "~/app/[...not_found]/page";
import useOnlineStatus from "./use-online-status";

export function SurveyQuestionnaire({
session,
Expand Down Expand Up @@ -62,82 +63,48 @@ export function SurveyQuestionnaire({

const screenSize = useScreenSize();

const isOnline = useOnlineStatus();

const [previouslyOffline, setPreviouslyOffline] = useState(false);

useEffect(() => {
let PreviouslyOffline = false;
console.log("isOnline", isOnline);
const handleOnline = async () => {
if (PreviouslyOffline) {
if (previouslyOffline) {
try {
await SaveResponsesToDatabase(responses, session, submitResponse);
toast({
title: "Back online!",
description:
"Your (intermediate) responses have been submitted successfully.",
});
} catch (error) {
toast({
title: "Failed to resend responses",
description:
"An error occurred while attempting to resend responses.",
variant: "destructive",
});
console.error("Error in online submission:", error);
}
PreviouslyOffline = false;
setPreviouslyOffline(false);
}
};

const handleOffline = () => {
PreviouslyOffline = true;
console.log("Offline - Failed to save responses. Retrying...");
// Display error toast if offline
toast({
title: "Failed to save responses. Retrying...",
description:
"Data submission in progress... Your responses will be automatically submitted once you're back online. Feel free to continue filling out the survey.",
variant: "informative",
});
};
if (!navigator.onLine) {
// Handle offline when component mounts
handleOffline();
if (!isOnline) {
setPreviouslyOffline(true);
} else {
handleOnline().catch(() => {
toast({
title: "Failed to resend responses",
description:
"An error occurred while attempting to resend responses.",
variant: "destructive",
});
console.log("Failed to save responses");
});
}
}, [isOnline, previouslyOffline, responses, session, submitResponse]);

// Add event listeners for online and offline events
window.addEventListener("online", () => {
handleOnline().catch(() => {
toast({
title: "Failed to resend responses",
description:
"An error occurred while attempting to resend responses.",
variant: "destructive",
});
useEffect(() => {
if (isOnline && previouslyOffline) {
toast({
title: "Back online!",
description:
"Your (intermediate) responses have been submitted successfully.",
});
});
window.addEventListener("offline", handleOffline);

return () => {
// Remove event listeners when component unmounts
window.addEventListener("online", () => {
handleOnline().catch(() => {
toast({
title: "Failed to resend responses",
description:
"An error occurred while attempting to resend responses.",
variant: "destructive",
});
});
} else if (!isOnline) {
toast({
title: "Failed to save responses. Retrying...",
description:
"Data submission in progress... Your responses will be automatically submitted once you're back online. Feel free to continue filling out the survey.",
variant: "informative",
});
window.removeEventListener("offline", handleOffline);
};
}, [responses, session, submitResponse]);
}
}, [isOnline, previouslyOffline]);

if (!roleExists) {
return renderNotFoundPage();
Expand Down Expand Up @@ -259,8 +226,8 @@ export function SurveyQuestionnaire({
/>
<SpinnerButton
type="submit"
state={isSubmitting || submitResponse.isLoading}
disabled={isSubmitting || submitResponse.isLoading}
state={isSubmitting || submitResponse.isLoading || !isOnline}
disabled={isSubmitting || submitResponse.isLoading || !isOnline}
name={getNextHref(selectedRolesForProgressBar) ? "Next" : "Submit"}
/>
</form>
Expand Down
27 changes: 27 additions & 0 deletions src/components/use-online-status.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"use client";

import { useState, useEffect } from "react";

function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(true);

useEffect(() => {
setIsOnline(window.navigator && window.navigator.onLine);
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);

return isOnline;
}

export default useOnlineStatus;
File renamed without changes.
11 changes: 1 addition & 10 deletions src/utils/submission-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,7 @@ import { api } from "~/trpc/react";
export const useSubmission = () => {
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);

const submitResponse = api.survey.setQuestionResult.useMutation({
onSuccess: () => {
console.log("Response submitted successfully");
return true;
},
onError: (error) => {
console.error("Error submitting response:", error);
return false;
},
});
const submitResponse = api.survey.setQuestionResult.useMutation();

return { isSubmitting, setIsSubmitting, submitResponse };
};
1 change: 0 additions & 1 deletion src/utils/survey-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,6 @@ export async function SaveResponsesToDatabase(

// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
await Promise.all([submitResponse.mutateAsync(mappedResponsesWithUserId)]);
console.log("Responses saved successfully");
return true;
} catch (error) {
console.error("Error saving responses:", error);
Expand Down

0 comments on commit cdd01cf

Please sign in to comment.