From f4528ab344a63d82a27852415e2e99544045cbd6 Mon Sep 17 00:00:00 2001
From: Felipe D'Abrantes <felidabrantes@gmail>
Date: Fri, 21 Apr 2023 19:16:14 +0100
Subject: [PATCH] Add use hook for Questions

---
 .../src/hooks/useQuestions.ts                 | 41 +++++++++++++++++++
 1 file changed, 41 insertions(+)
 create mode 100644 daily-thought-frontend/src/hooks/useQuestions.ts

diff --git a/daily-thought-frontend/src/hooks/useQuestions.ts b/daily-thought-frontend/src/hooks/useQuestions.ts
new file mode 100644
index 00000000..de67e315
--- /dev/null
+++ b/daily-thought-frontend/src/hooks/useQuestions.ts
@@ -0,0 +1,41 @@
+import { useState, useEffect } from 'react';
+
+export type QuestionRecord = {
+  id: string;
+  content: string;
+  used: number;
+  createdAt: string;
+  updatedAt: string;
+};
+
+export const useQuestions = () => {
+  const [rehydrateQuestions, setRehydrateQuestions] = useState(false);
+  const [questions, setQuestions] = useState<undefined | QuestionRecord[]>(undefined);
+
+  useEffect(() => {
+    if (questions !== undefined) return;
+    setRehydrateQuestions(true);
+  }, [questions]);
+
+  const fetchQuestions = async () => {
+    const endpoint = `${process.env.NEXT_PUBLIC_FEED_SERVICE_URL}questions`;
+    const headers = { Authorization: `Bearer ${sessionStorage.getItem('token')}` };
+
+    const response = await fetch(endpoint, { headers });
+    if (response.ok) {
+      const data = await response.json();
+      return data;
+    }
+  };
+
+  useEffect(() => {
+    if (!rehydrateQuestions) return;
+
+    fetchQuestions().then((res: QuestionRecord[]) => {
+      setQuestions(res);
+      setRehydrateQuestions(false);
+    });
+  }, [rehydrateQuestions]);
+
+  return { questions, setRehydrateQuestions };
+};
-- 
GitLab