From 68138f0dcd8b3db2c23b31a20508726f245b5ba5 Mon Sep 17 00:00:00 2001
From: Armand Philippot <git@armandphilippot.com>
Date: Mon, 17 Jan 2022 17:13:51 +0100
Subject: feat: implement dark mode

---
 src/components/ThemeToggle/ThemeToggle.tsx | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

(limited to 'src/components/ThemeToggle/ThemeToggle.tsx')

diff --git a/src/components/ThemeToggle/ThemeToggle.tsx b/src/components/ThemeToggle/ThemeToggle.tsx
index 4b93ac9..c44f6df 100644
--- a/src/components/ThemeToggle/ThemeToggle.tsx
+++ b/src/components/ThemeToggle/ThemeToggle.tsx
@@ -1,16 +1,27 @@
 import { Form } from '@components/Form';
 import { MoonIcon, SunIcon } from '@components/Icons';
+import Spinner from '@components/Spinner/Spinner';
 import { t } from '@lingui/macro';
-import { FormEvent, useState } from 'react';
+import { useTheme } from 'next-themes';
+import { FormEvent, useEffect, useState } from 'react';
 import styles from './ThemeToggle.module.scss';
 
 const ThemeToggle = () => {
-  const [isDarkTheme, setIsDarkTheme] = useState<boolean>(false);
+  const [isMounted, setIsMounted] = useState<boolean>(false);
+  const { resolvedTheme, setTheme } = useTheme();
+
+  useEffect(() => {
+    setIsMounted(true);
+  }, []);
 
   const onSubmit = (e: FormEvent) => {
     e.preventDefault();
   };
 
+  if (!isMounted) return <Spinner />;
+
+  const isDarkTheme = resolvedTheme === 'dark';
+
   return (
     <Form modifier="theme" submitHandler={onSubmit}>
       <input
@@ -19,7 +30,7 @@ const ThemeToggle = () => {
         id="dark-theme"
         name="dark-theme"
         checked={isDarkTheme}
-        onChange={() => setIsDarkTheme(!isDarkTheme)}
+        onChange={() => setTheme(isDarkTheme ? 'light' : 'dark')}
       />
       <label htmlFor="dark-theme" className={styles.label}>
         <span className={styles.title}>{t`Theme:`}</span>
-- 
cgit v1.2.3

